blob: fd208300f546d2f812f566cbb3d6494af609e9a3 [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;
Adam Sawicki5268dbb2017-11-08 12:52:05 +0100304 vbAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_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;
Adam Sawicki5268dbb2017-11-08 12:52:05 +0100329 ibAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_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 Sawickie6e498f2017-06-16 17:21:31 +0200367static void CreateTexture(uint32_t sizeX, uint32_t sizeY)
368{
369 // Create Image
370
371 const VkDeviceSize imageSize = sizeX * sizeY * 4;
372
373 VkImageCreateInfo stagingImageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
374 stagingImageInfo.imageType = VK_IMAGE_TYPE_2D;
375 stagingImageInfo.extent.width = sizeX;
376 stagingImageInfo.extent.height = sizeY;
377 stagingImageInfo.extent.depth = 1;
378 stagingImageInfo.mipLevels = 1;
379 stagingImageInfo.arrayLayers = 1;
380 stagingImageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
381 stagingImageInfo.tiling = VK_IMAGE_TILING_LINEAR;
382 stagingImageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
383 stagingImageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
384 stagingImageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
385 stagingImageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
386 stagingImageInfo.flags = 0;
Adam Sawicki819860e2017-07-04 14:30:38 +0200387
Adam Sawicki976f9202017-09-12 20:45:14 +0200388 VmaAllocationCreateInfo stagingImageAllocCreateInfo = {};
389 stagingImageAllocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
Adam Sawicki5268dbb2017-11-08 12:52:05 +0100390 stagingImageAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
Adam Sawicki819860e2017-07-04 14:30:38 +0200391
Adam Sawickie6e498f2017-06-16 17:21:31 +0200392 VkImage stagingImage = VK_NULL_HANDLE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200393 VmaAllocation stagingImageAlloc = VK_NULL_HANDLE;
394 VmaAllocationInfo stagingImageAllocInfo = {};
Adam Sawicki976f9202017-09-12 20:45:14 +0200395 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &stagingImageInfo, &stagingImageAllocCreateInfo, &stagingImage, &stagingImageAlloc, &stagingImageAllocInfo) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200396
397 VkImageSubresource imageSubresource = {};
398 imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
399 imageSubresource.mipLevel = 0;
400 imageSubresource.arrayLayer = 0;
401
402 VkSubresourceLayout imageLayout = {};
403 vkGetImageSubresourceLayout(g_hDevice, stagingImage, &imageSubresource, &imageLayout);
404
Adam Sawicki819860e2017-07-04 14:30:38 +0200405 char* const pMipLevelData = (char*)stagingImageAllocInfo.pMappedData + imageLayout.offset;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200406 uint8_t* pRowData = (uint8_t*)pMipLevelData;
407 for(uint32_t y = 0; y < sizeY; ++y)
408 {
409 uint32_t* pPixelData = (uint32_t*)pRowData;
410 for(uint32_t x = 0; x < sizeY; ++x)
411 {
412 *pPixelData =
413 ((x & 0x18) == 0x08 ? 0x000000FF : 0x00000000) |
414 ((x & 0x18) == 0x10 ? 0x0000FFFF : 0x00000000) |
415 ((y & 0x18) == 0x08 ? 0x0000FF00 : 0x00000000) |
416 ((y & 0x18) == 0x10 ? 0x00FF0000 : 0x00000000);
417 ++pPixelData;
418 }
419 pRowData += imageLayout.rowPitch;
420 }
421
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200422 // No need to flush stagingImage memory because CPU_ONLY memory is always HOST_COHERENT.
423
Adam Sawicki10844a82017-08-16 17:32:09 +0200424 // Create g_hTextureImage in GPU memory.
425
Adam Sawickie6e498f2017-06-16 17:21:31 +0200426 VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
427 imageInfo.imageType = VK_IMAGE_TYPE_2D;
428 imageInfo.extent.width = sizeX;
429 imageInfo.extent.height = sizeY;
430 imageInfo.extent.depth = 1;
431 imageInfo.mipLevels = 1;
432 imageInfo.arrayLayers = 1;
433 imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
434 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
435 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
436 imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
437 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
438 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
439 imageInfo.flags = 0;
Adam Sawicki10844a82017-08-16 17:32:09 +0200440
Adam Sawicki976f9202017-09-12 20:45:14 +0200441 VmaAllocationCreateInfo imageAllocCreateInfo = {};
442 imageAllocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawicki10844a82017-08-16 17:32:09 +0200443
Adam Sawicki976f9202017-09-12 20:45:14 +0200444 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &imageInfo, &imageAllocCreateInfo, &g_hTextureImage, &g_hTextureImageAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200445
Adam Sawicki10844a82017-08-16 17:32:09 +0200446 // Transition image layouts, copy image.
447
448 BeginSingleTimeCommands();
449
450 VkImageMemoryBarrier imgMemBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
451 imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
452 imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
453 imgMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
454 imgMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
455 imgMemBarrier.image = stagingImage;
456 imgMemBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
457 imgMemBarrier.subresourceRange.baseMipLevel = 0;
458 imgMemBarrier.subresourceRange.levelCount = 1;
459 imgMemBarrier.subresourceRange.baseArrayLayer = 0;
460 imgMemBarrier.subresourceRange.layerCount = 1;
461 imgMemBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
462 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
463
464 vkCmdPipelineBarrier(
465 g_hTemporaryCommandBuffer,
466 VK_PIPELINE_STAGE_HOST_BIT,
467 VK_PIPELINE_STAGE_TRANSFER_BIT,
468 0,
469 0, nullptr,
470 0, nullptr,
471 1, &imgMemBarrier);
472
473 imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
474 imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
475 imgMemBarrier.image = g_hTextureImage;
476 imgMemBarrier.srcAccessMask = 0;
477 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
478
479 vkCmdPipelineBarrier(
480 g_hTemporaryCommandBuffer,
481 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
482 VK_PIPELINE_STAGE_TRANSFER_BIT,
483 0,
484 0, nullptr,
485 0, nullptr,
486 1, &imgMemBarrier);
487
488 VkImageCopy imageCopy = {};
489 imageCopy.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
490 imageCopy.srcSubresource.baseArrayLayer = 0;
491 imageCopy.srcSubresource.mipLevel = 0;
492 imageCopy.srcSubresource.layerCount = 1;
493 imageCopy.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
494 imageCopy.dstSubresource.baseArrayLayer = 0;
495 imageCopy.dstSubresource.mipLevel = 0;
496 imageCopy.dstSubresource.layerCount = 1;
497 imageCopy.srcOffset.x = 0;
498 imageCopy.srcOffset.y = 0;
499 imageCopy.srcOffset.z = 0;
500 imageCopy.dstOffset.x = 0;
501 imageCopy.dstOffset.y = 0;
502 imageCopy.dstOffset.z = 0;
503 imageCopy.extent.width = sizeX;
504 imageCopy.extent.height = sizeY;
505 imageCopy.extent.depth = 1;
506 vkCmdCopyImage(
507 g_hTemporaryCommandBuffer,
508 stagingImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
509 g_hTextureImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
510 1, &imageCopy);
511
512 imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
513 imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
514 imgMemBarrier.image = g_hTextureImage;
515 imgMemBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
516 imgMemBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
517
518 vkCmdPipelineBarrier(
519 g_hTemporaryCommandBuffer,
520 VK_PIPELINE_STAGE_TRANSFER_BIT,
521 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
522 0,
523 0, nullptr,
524 0, nullptr,
525 1, &imgMemBarrier);
526
527 EndSingleTimeCommands();
Adam Sawickie6e498f2017-06-16 17:21:31 +0200528
Adam Sawicki819860e2017-07-04 14:30:38 +0200529 vmaDestroyImage(g_hAllocator, stagingImage, stagingImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200530
531 // Create ImageView
532
533 VkImageViewCreateInfo textureImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
534 textureImageViewInfo.image = g_hTextureImage;
535 textureImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
536 textureImageViewInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
537 textureImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
538 textureImageViewInfo.subresourceRange.baseMipLevel = 0;
539 textureImageViewInfo.subresourceRange.levelCount = 1;
540 textureImageViewInfo.subresourceRange.baseArrayLayer = 0;
541 textureImageViewInfo.subresourceRange.layerCount = 1;
542 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &textureImageViewInfo, nullptr, &g_hTextureImageView) );
543}
544
545struct UniformBufferObject
546{
547 mathfu::vec4_packed ModelViewProj[4];
548};
549
550static void RegisterDebugCallbacks()
551{
552 g_pvkCreateDebugReportCallbackEXT =
553 reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>
554 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkCreateDebugReportCallbackEXT"));
555 g_pvkDebugReportMessageEXT =
556 reinterpret_cast<PFN_vkDebugReportMessageEXT>
557 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkDebugReportMessageEXT"));
558 g_pvkDestroyDebugReportCallbackEXT =
559 reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>
560 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkDestroyDebugReportCallbackEXT"));
561 assert(g_pvkCreateDebugReportCallbackEXT);
562 assert(g_pvkDebugReportMessageEXT);
563 assert(g_pvkDestroyDebugReportCallbackEXT);
564
565 VkDebugReportCallbackCreateInfoEXT callbackCreateInfo;
566 callbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
567 callbackCreateInfo.pNext = nullptr;
568 callbackCreateInfo.flags = //VK_DEBUG_REPORT_INFORMATION_BIT_EXT |
569 VK_DEBUG_REPORT_ERROR_BIT_EXT |
570 VK_DEBUG_REPORT_WARNING_BIT_EXT |
571 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT /*|
572 VK_DEBUG_REPORT_DEBUG_BIT_EXT*/;
573 callbackCreateInfo.pfnCallback = &MyDebugReportCallback;
574 callbackCreateInfo.pUserData = nullptr;
575
576 ERR_GUARD_VULKAN( g_pvkCreateDebugReportCallbackEXT(g_hVulkanInstance, &callbackCreateInfo, nullptr, &g_hCallback) );
577}
578
579static bool IsLayerSupported(const VkLayerProperties* pProps, size_t propCount, const char* pLayerName)
580{
581 const VkLayerProperties* propsEnd = pProps + propCount;
582 return std::find_if(
583 pProps,
584 propsEnd,
585 [pLayerName](const VkLayerProperties& prop) -> bool {
586 return strcmp(pLayerName, prop.layerName) == 0;
587 }) != propsEnd;
588}
589
590static VkFormat FindSupportedFormat(
591 const std::vector<VkFormat>& candidates,
592 VkImageTiling tiling,
593 VkFormatFeatureFlags features)
594{
595 for (VkFormat format : candidates)
596 {
597 VkFormatProperties props;
598 vkGetPhysicalDeviceFormatProperties(g_hPhysicalDevice, format, &props);
599
600 if ((tiling == VK_IMAGE_TILING_LINEAR) &&
601 ((props.linearTilingFeatures & features) == features))
602 {
603 return format;
604 }
605 else if ((tiling == VK_IMAGE_TILING_OPTIMAL) &&
606 ((props.optimalTilingFeatures & features) == features))
607 {
608 return format;
609 }
610 }
611 return VK_FORMAT_UNDEFINED;
612}
613
614static VkFormat FindDepthFormat()
615{
616 std::vector<VkFormat> formats;
617 formats.push_back(VK_FORMAT_D32_SFLOAT);
618 formats.push_back(VK_FORMAT_D32_SFLOAT_S8_UINT);
619 formats.push_back(VK_FORMAT_D24_UNORM_S8_UINT);
620
621 return FindSupportedFormat(
622 formats,
623 VK_IMAGE_TILING_OPTIMAL,
624 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
625}
626
627static void CreateSwapchain()
628{
629 // Query surface formats.
630
631 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_hPhysicalDevice, g_hSurface, &g_SurfaceCapabilities) );
632
633 uint32_t formatCount = 0;
634 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, nullptr) );
635 g_SurfaceFormats.resize(formatCount);
636 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, g_SurfaceFormats.data()) );
637
638 uint32_t presentModeCount = 0;
639 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, nullptr) );
640 g_PresentModes.resize(presentModeCount);
641 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, g_PresentModes.data()) );
642
643 // Create swap chain
644
645 g_SurfaceFormat = ChooseSurfaceFormat();
646 VkPresentModeKHR presentMode = ChooseSwapPresentMode();
647 g_Extent = ChooseSwapExtent();
648
649 uint32_t imageCount = g_SurfaceCapabilities.minImageCount + 1;
650 if((g_SurfaceCapabilities.maxImageCount > 0) &&
651 (imageCount > g_SurfaceCapabilities.maxImageCount))
652 {
653 imageCount = g_SurfaceCapabilities.maxImageCount;
654 }
655
656 VkSwapchainCreateInfoKHR swapChainInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
657 swapChainInfo.surface = g_hSurface;
658 swapChainInfo.minImageCount = imageCount;
659 swapChainInfo.imageFormat = g_SurfaceFormat.format;
660 swapChainInfo.imageColorSpace = g_SurfaceFormat.colorSpace;
661 swapChainInfo.imageExtent = g_Extent;
662 swapChainInfo.imageArrayLayers = 1;
663 swapChainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
664 swapChainInfo.preTransform = g_SurfaceCapabilities.currentTransform;
665 swapChainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
666 swapChainInfo.presentMode = presentMode;
667 swapChainInfo.clipped = VK_TRUE;
668 swapChainInfo.oldSwapchain = g_hSwapchain;
669
670 uint32_t queueFamilyIndices[] = { g_GraphicsQueueFamilyIndex, g_PresentQueueFamilyIndex };
671 if(g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex)
672 {
673 swapChainInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
674 swapChainInfo.queueFamilyIndexCount = 2;
675 swapChainInfo.pQueueFamilyIndices = queueFamilyIndices;
676 }
677 else
678 {
679 swapChainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
680 }
681
682 VkSwapchainKHR hNewSwapchain = VK_NULL_HANDLE;
683 ERR_GUARD_VULKAN( vkCreateSwapchainKHR(g_hDevice, &swapChainInfo, nullptr, &hNewSwapchain) );
684 if(g_hSwapchain != VK_NULL_HANDLE)
685 vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, nullptr);
686 g_hSwapchain = hNewSwapchain;
687
688 // Retrieve swapchain images.
689
690 uint32_t swapchainImageCount = 0;
691 ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, nullptr) );
692 g_SwapchainImages.resize(swapchainImageCount);
693 ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, g_SwapchainImages.data()) );
694
695 // Create swapchain image views.
696
697 for(size_t i = g_SwapchainImageViews.size(); i--; )
698 vkDestroyImageView(g_hDevice, g_SwapchainImageViews[i], nullptr);
699 g_SwapchainImageViews.clear();
700
701 VkImageViewCreateInfo swapchainImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
702 g_SwapchainImageViews.resize(swapchainImageCount);
703 for(uint32_t i = 0; i < swapchainImageCount; ++i)
704 {
705 swapchainImageViewInfo.image = g_SwapchainImages[i];
706 swapchainImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
707 swapchainImageViewInfo.format = g_SurfaceFormat.format;
708 swapchainImageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
709 swapchainImageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
710 swapchainImageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
711 swapchainImageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
712 swapchainImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
713 swapchainImageViewInfo.subresourceRange.baseMipLevel = 0;
714 swapchainImageViewInfo.subresourceRange.levelCount = 1;
715 swapchainImageViewInfo.subresourceRange.baseArrayLayer = 0;
716 swapchainImageViewInfo.subresourceRange.layerCount = 1;
717 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &swapchainImageViewInfo, nullptr, &g_SwapchainImageViews[i]) );
718 }
719
720 // Create depth buffer
721
722 g_DepthFormat = FindDepthFormat();
723 assert(g_DepthFormat != VK_FORMAT_UNDEFINED);
724
725 VkImageCreateInfo depthImageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
726 depthImageInfo.imageType = VK_IMAGE_TYPE_2D;
727 depthImageInfo.extent.width = g_Extent.width;
728 depthImageInfo.extent.height = g_Extent.height;
729 depthImageInfo.extent.depth = 1;
730 depthImageInfo.mipLevels = 1;
731 depthImageInfo.arrayLayers = 1;
732 depthImageInfo.format = g_DepthFormat;
733 depthImageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
734 depthImageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
735 depthImageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
736 depthImageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
737 depthImageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
738 depthImageInfo.flags = 0;
739
Adam Sawicki976f9202017-09-12 20:45:14 +0200740 VmaAllocationCreateInfo depthImageAllocCreateInfo = {};
741 depthImageAllocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200742
Adam Sawicki976f9202017-09-12 20:45:14 +0200743 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &depthImageInfo, &depthImageAllocCreateInfo, &g_hDepthImage, &g_hDepthImageAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200744
745 VkImageViewCreateInfo depthImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
746 depthImageViewInfo.image = g_hDepthImage;
747 depthImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
748 depthImageViewInfo.format = g_DepthFormat;
749 depthImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
750 depthImageViewInfo.subresourceRange.baseMipLevel = 0;
751 depthImageViewInfo.subresourceRange.levelCount = 1;
752 depthImageViewInfo.subresourceRange.baseArrayLayer = 0;
753 depthImageViewInfo.subresourceRange.layerCount = 1;
754
755 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &depthImageViewInfo, nullptr, &g_hDepthImageView) );
756
Adam Sawicki10844a82017-08-16 17:32:09 +0200757 BeginSingleTimeCommands();
758
Adam Sawicki3bd398a2017-11-13 16:10:38 +0100759 // Transition image layout of g_SwapchainImages.
760 for(uint32_t i = 0; i < swapchainImageCount; ++i)
761 {
762 VkImageMemoryBarrier imgMemBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
763 imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
764 imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
765 imgMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
766 imgMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
767 imgMemBarrier.image = g_SwapchainImages[i];
768 imgMemBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
769 imgMemBarrier.subresourceRange.baseMipLevel = 0;
770 imgMemBarrier.subresourceRange.levelCount = 1;
771 imgMemBarrier.subresourceRange.baseArrayLayer = 0;
772 imgMemBarrier.subresourceRange.layerCount = 1;
773 imgMemBarrier.srcAccessMask = 0;
774 imgMemBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
775
776 vkCmdPipelineBarrier(
777 g_hTemporaryCommandBuffer,
778 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
779 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
780 0,
781 0, nullptr,
782 0, nullptr,
783 1, &imgMemBarrier);
784 }
785
786 // Transition image layout of g_hDepthImage.
787
Adam Sawicki10844a82017-08-16 17:32:09 +0200788 VkImageMemoryBarrier imgMemBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
789 imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
790 imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
791 imgMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
792 imgMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
793 imgMemBarrier.image = g_hDepthImage;
794 imgMemBarrier.subresourceRange.aspectMask = g_DepthFormat == VK_FORMAT_D32_SFLOAT ?
795 VK_IMAGE_ASPECT_DEPTH_BIT :
796 VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
797 imgMemBarrier.subresourceRange.baseMipLevel = 0;
798 imgMemBarrier.subresourceRange.levelCount = 1;
799 imgMemBarrier.subresourceRange.baseArrayLayer = 0;
800 imgMemBarrier.subresourceRange.layerCount = 1;
801 imgMemBarrier.srcAccessMask = 0;
802 imgMemBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
803
804 vkCmdPipelineBarrier(
805 g_hTemporaryCommandBuffer,
806 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
807 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
808 0,
809 0, nullptr,
810 0, nullptr,
811 1, &imgMemBarrier);
812
813 EndSingleTimeCommands();
Adam Sawickie6e498f2017-06-16 17:21:31 +0200814
815 // Create pipeline layout
816 {
817 if(g_hPipelineLayout != VK_NULL_HANDLE)
818 {
819 vkDestroyPipelineLayout(g_hDevice, g_hPipelineLayout, nullptr);
820 g_hPipelineLayout = VK_NULL_HANDLE;
821 }
822
823 VkPushConstantRange pushConstantRanges[1];
824 ZeroMemory(&pushConstantRanges, sizeof pushConstantRanges);
825 pushConstantRanges[0].offset = 0;
826 pushConstantRanges[0].size = sizeof(UniformBufferObject);
827 pushConstantRanges[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
828
829 VkDescriptorSetLayout descriptorSetLayouts[] = { g_hDescriptorSetLayout };
830 VkPipelineLayoutCreateInfo pipelineLayoutInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
831 pipelineLayoutInfo.setLayoutCount = 1;
832 pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts;
833 pipelineLayoutInfo.pushConstantRangeCount = 1;
834 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
835 ERR_GUARD_VULKAN( vkCreatePipelineLayout(g_hDevice, &pipelineLayoutInfo, nullptr, &g_hPipelineLayout) );
836 }
837
838 // Create render pass
839 {
840 if(g_hRenderPass != VK_NULL_HANDLE)
841 {
842 vkDestroyRenderPass(g_hDevice, g_hRenderPass, nullptr);
843 g_hRenderPass = VK_NULL_HANDLE;
844 }
845
846 VkAttachmentDescription attachments[2];
847 ZeroMemory(attachments, sizeof(attachments));
848
849 attachments[0].format = g_SurfaceFormat.format;
850 attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
851 attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
852 attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
853 attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
854 attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
Adam Sawicki3bd398a2017-11-13 16:10:38 +0100855 attachments[0].initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200856 attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
857
858 attachments[1].format = g_DepthFormat;
859 attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
860 attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
861 attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
862 attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
863 attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
Adam Sawicki3bd398a2017-11-13 16:10:38 +0100864 attachments[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200865 attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
866
867 VkAttachmentReference colorAttachmentRef = {};
868 colorAttachmentRef.attachment = 0;
869 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
870
871 VkAttachmentReference depthStencilAttachmentRef = {};
872 depthStencilAttachmentRef.attachment = 1;
873 depthStencilAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
874
875 VkSubpassDescription subpassDesc = {};
876 subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
877 subpassDesc.colorAttachmentCount = 1;
878 subpassDesc.pColorAttachments = &colorAttachmentRef;
879 subpassDesc.pDepthStencilAttachment = &depthStencilAttachmentRef;
880
Adam Sawickie6e498f2017-06-16 17:21:31 +0200881 VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };
882 renderPassInfo.attachmentCount = (uint32_t)_countof(attachments);
883 renderPassInfo.pAttachments = attachments;
884 renderPassInfo.subpassCount = 1;
885 renderPassInfo.pSubpasses = &subpassDesc;
Adam Sawicki14137d12017-10-16 18:06:05 +0200886 renderPassInfo.dependencyCount = 0;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200887 ERR_GUARD_VULKAN( vkCreateRenderPass(g_hDevice, &renderPassInfo, nullptr, &g_hRenderPass) );
888 }
889
890 // Create pipeline
891 {
892 std::vector<char> vertShaderCode;
893 LoadShader(vertShaderCode, "Shader.vert.spv");
894 VkShaderModuleCreateInfo shaderModuleInfo = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
895 shaderModuleInfo.codeSize = vertShaderCode.size();
896 shaderModuleInfo.pCode = (const uint32_t*)vertShaderCode.data();
897 VkShaderModule hVertShaderModule = VK_NULL_HANDLE;
898 ERR_GUARD_VULKAN( vkCreateShaderModule(g_hDevice, &shaderModuleInfo, nullptr, &hVertShaderModule) );
899
900 std::vector<char> hFragShaderCode;
901 LoadShader(hFragShaderCode, "Shader.frag.spv");
902 shaderModuleInfo.codeSize = hFragShaderCode.size();
903 shaderModuleInfo.pCode = (const uint32_t*)hFragShaderCode.data();
904 VkShaderModule fragShaderModule = VK_NULL_HANDLE;
905 ERR_GUARD_VULKAN( vkCreateShaderModule(g_hDevice, &shaderModuleInfo, nullptr, &fragShaderModule) );
906
907 VkPipelineShaderStageCreateInfo vertPipelineShaderStageInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
908 vertPipelineShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
909 vertPipelineShaderStageInfo.module = hVertShaderModule;
910 vertPipelineShaderStageInfo.pName = "main";
911
912 VkPipelineShaderStageCreateInfo fragPipelineShaderStageInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
913 fragPipelineShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
914 fragPipelineShaderStageInfo.module = fragShaderModule;
915 fragPipelineShaderStageInfo.pName = "main";
916
917 VkPipelineShaderStageCreateInfo pipelineShaderStageInfos[] = {
918 vertPipelineShaderStageInfo,
919 fragPipelineShaderStageInfo
920 };
921
922 VkVertexInputBindingDescription bindingDescription = {};
923 bindingDescription.binding = 0;
924 bindingDescription.stride = sizeof(Vertex);
925 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
926
927 VkVertexInputAttributeDescription attributeDescriptions[3];
928 ZeroMemory(attributeDescriptions, sizeof(attributeDescriptions));
929
930 attributeDescriptions[0].binding = 0;
931 attributeDescriptions[0].location = 0;
932 attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
933 attributeDescriptions[0].offset = offsetof(Vertex, pos);
934
935 attributeDescriptions[1].binding = 0;
936 attributeDescriptions[1].location = 1;
937 attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
938 attributeDescriptions[1].offset = offsetof(Vertex, color);
939
940 attributeDescriptions[2].binding = 0;
941 attributeDescriptions[2].location = 2;
942 attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
943 attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
944
945 VkPipelineVertexInputStateCreateInfo pipelineVertexInputStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
946 pipelineVertexInputStateInfo.vertexBindingDescriptionCount = 1;
947 pipelineVertexInputStateInfo.pVertexBindingDescriptions = &bindingDescription;
948 pipelineVertexInputStateInfo.vertexAttributeDescriptionCount = _countof(attributeDescriptions);
949 pipelineVertexInputStateInfo.pVertexAttributeDescriptions = attributeDescriptions;
950
951 VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO };
952 pipelineInputAssemblyStateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
953 pipelineInputAssemblyStateInfo.primitiveRestartEnable = VK_TRUE;
954
955 VkViewport viewport = {};
956 viewport.x = 0.f;
957 viewport.y = 0.f;
958 viewport.width = (float)g_Extent.width;
959 viewport.height = (float)g_Extent.height;
960 viewport.minDepth = 0.f;
961 viewport.maxDepth = 1.f;
962
963 VkRect2D scissor = {};
964 scissor.offset.x = 0;
965 scissor.offset.y = 0;
966 scissor.extent = g_Extent;
967
968 VkPipelineViewportStateCreateInfo pipelineViewportStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO };
969 pipelineViewportStateInfo.viewportCount = 1;
970 pipelineViewportStateInfo.pViewports = &viewport;
971 pipelineViewportStateInfo.scissorCount = 1;
972 pipelineViewportStateInfo.pScissors = &scissor;
973
974 VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO };
975 pipelineRasterizationStateInfo.depthClampEnable = VK_FALSE;
976 pipelineRasterizationStateInfo.rasterizerDiscardEnable = VK_FALSE;
977 pipelineRasterizationStateInfo.polygonMode = VK_POLYGON_MODE_FILL;
978 pipelineRasterizationStateInfo.lineWidth = 1.f;
979 pipelineRasterizationStateInfo.cullMode = VK_CULL_MODE_BACK_BIT;
980 pipelineRasterizationStateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
981 pipelineRasterizationStateInfo.depthBiasEnable = VK_FALSE;
982 pipelineRasterizationStateInfo.depthBiasConstantFactor = 0.f;
983 pipelineRasterizationStateInfo.depthBiasClamp = 0.f;
984 pipelineRasterizationStateInfo.depthBiasSlopeFactor = 0.f;
985
986 VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO };
987 pipelineMultisampleStateInfo.sampleShadingEnable = VK_FALSE;
988 pipelineMultisampleStateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
989 pipelineMultisampleStateInfo.minSampleShading = 1.f;
990 pipelineMultisampleStateInfo.pSampleMask = nullptr;
991 pipelineMultisampleStateInfo.alphaToCoverageEnable = VK_FALSE;
992 pipelineMultisampleStateInfo.alphaToOneEnable = VK_FALSE;
993
994 VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState = {};
995 pipelineColorBlendAttachmentState.colorWriteMask =
996 VK_COLOR_COMPONENT_R_BIT |
997 VK_COLOR_COMPONENT_G_BIT |
998 VK_COLOR_COMPONENT_B_BIT |
999 VK_COLOR_COMPONENT_A_BIT;
1000 pipelineColorBlendAttachmentState.blendEnable = VK_FALSE;
1001 pipelineColorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
1002 pipelineColorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
1003 pipelineColorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; // Optional
1004 pipelineColorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
1005 pipelineColorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
1006 pipelineColorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
1007
1008 VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO };
1009 pipelineColorBlendStateInfo.logicOpEnable = VK_FALSE;
1010 pipelineColorBlendStateInfo.logicOp = VK_LOGIC_OP_COPY;
1011 pipelineColorBlendStateInfo.attachmentCount = 1;
1012 pipelineColorBlendStateInfo.pAttachments = &pipelineColorBlendAttachmentState;
1013
1014 VkPipelineDepthStencilStateCreateInfo depthStencilStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
1015 depthStencilStateInfo.depthTestEnable = VK_TRUE;
1016 depthStencilStateInfo.depthWriteEnable = VK_TRUE;
1017 depthStencilStateInfo.depthCompareOp = VK_COMPARE_OP_LESS;
1018 depthStencilStateInfo.depthBoundsTestEnable = VK_FALSE;
1019 depthStencilStateInfo.stencilTestEnable = VK_FALSE;
1020
1021 VkGraphicsPipelineCreateInfo pipelineInfo = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO };
1022 pipelineInfo.stageCount = 2;
1023 pipelineInfo.pStages = pipelineShaderStageInfos;
1024 pipelineInfo.pVertexInputState = &pipelineVertexInputStateInfo;
1025 pipelineInfo.pInputAssemblyState = &pipelineInputAssemblyStateInfo;
1026 pipelineInfo.pViewportState = &pipelineViewportStateInfo;
1027 pipelineInfo.pRasterizationState = &pipelineRasterizationStateInfo;
1028 pipelineInfo.pMultisampleState = &pipelineMultisampleStateInfo;
1029 pipelineInfo.pDepthStencilState = &depthStencilStateInfo;
1030 pipelineInfo.pColorBlendState = &pipelineColorBlendStateInfo;
1031 pipelineInfo.pDynamicState = nullptr;
1032 pipelineInfo.layout = g_hPipelineLayout;
1033 pipelineInfo.renderPass = g_hRenderPass;
1034 pipelineInfo.subpass = 0;
1035 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
1036 pipelineInfo.basePipelineIndex = -1;
1037 ERR_GUARD_VULKAN( vkCreateGraphicsPipelines(
1038 g_hDevice,
1039 VK_NULL_HANDLE,
1040 1,
1041 &pipelineInfo, nullptr,
1042 &g_hPipeline) );
1043
1044 vkDestroyShaderModule(g_hDevice, fragShaderModule, nullptr);
1045 vkDestroyShaderModule(g_hDevice, hVertShaderModule, nullptr);
1046 }
1047
1048 // Create frambuffers
1049
1050 for(size_t i = g_Framebuffers.size(); i--; )
1051 vkDestroyFramebuffer(g_hDevice, g_Framebuffers[i], nullptr);
1052 g_Framebuffers.clear();
1053
1054 g_Framebuffers.resize(g_SwapchainImageViews.size());
1055 for(size_t i = 0; i < g_SwapchainImages.size(); ++i)
1056 {
1057 VkImageView attachments[] = { g_SwapchainImageViews[i], g_hDepthImageView };
1058
1059 VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
1060 framebufferInfo.renderPass = g_hRenderPass;
1061 framebufferInfo.attachmentCount = (uint32_t)_countof(attachments);
1062 framebufferInfo.pAttachments = attachments;
1063 framebufferInfo.width = g_Extent.width;
1064 framebufferInfo.height = g_Extent.height;
1065 framebufferInfo.layers = 1;
1066 ERR_GUARD_VULKAN( vkCreateFramebuffer(g_hDevice, &framebufferInfo, nullptr, &g_Framebuffers[i]) );
1067 }
1068
1069 // Create semaphores
1070
1071 if(g_hImageAvailableSemaphore != VK_NULL_HANDLE)
1072 {
1073 vkDestroySemaphore(g_hDevice, g_hImageAvailableSemaphore, nullptr);
1074 g_hImageAvailableSemaphore = VK_NULL_HANDLE;
1075 }
1076 if(g_hRenderFinishedSemaphore != VK_NULL_HANDLE)
1077 {
1078 vkDestroySemaphore(g_hDevice, g_hRenderFinishedSemaphore, nullptr);
1079 g_hRenderFinishedSemaphore = VK_NULL_HANDLE;
1080 }
1081
1082 VkSemaphoreCreateInfo semaphoreInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
1083 ERR_GUARD_VULKAN( vkCreateSemaphore(g_hDevice, &semaphoreInfo, nullptr, &g_hImageAvailableSemaphore) );
1084 ERR_GUARD_VULKAN( vkCreateSemaphore(g_hDevice, &semaphoreInfo, nullptr, &g_hRenderFinishedSemaphore) );
1085}
1086
1087static void DestroySwapchain(bool destroyActualSwapchain)
1088{
1089 if(g_hImageAvailableSemaphore != VK_NULL_HANDLE)
1090 {
1091 vkDestroySemaphore(g_hDevice, g_hImageAvailableSemaphore, nullptr);
1092 g_hImageAvailableSemaphore = VK_NULL_HANDLE;
1093 }
1094 if(g_hRenderFinishedSemaphore != VK_NULL_HANDLE)
1095 {
1096 vkDestroySemaphore(g_hDevice, g_hRenderFinishedSemaphore, nullptr);
1097 g_hRenderFinishedSemaphore = VK_NULL_HANDLE;
1098 }
1099
1100 for(size_t i = g_Framebuffers.size(); i--; )
1101 vkDestroyFramebuffer(g_hDevice, g_Framebuffers[i], nullptr);
1102 g_Framebuffers.clear();
1103
1104 if(g_hDepthImageView != VK_NULL_HANDLE)
1105 {
1106 vkDestroyImageView(g_hDevice, g_hDepthImageView, nullptr);
1107 g_hDepthImageView = VK_NULL_HANDLE;
1108 }
1109 if(g_hDepthImage != VK_NULL_HANDLE)
1110 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001111 vmaDestroyImage(g_hAllocator, g_hDepthImage, g_hDepthImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001112 g_hDepthImage = VK_NULL_HANDLE;
1113 }
1114
1115 if(g_hPipeline != VK_NULL_HANDLE)
1116 {
1117 vkDestroyPipeline(g_hDevice, g_hPipeline, nullptr);
1118 g_hPipeline = VK_NULL_HANDLE;
1119 }
1120
1121 if(g_hRenderPass != VK_NULL_HANDLE)
1122 {
1123 vkDestroyRenderPass(g_hDevice, g_hRenderPass, nullptr);
1124 g_hRenderPass = VK_NULL_HANDLE;
1125 }
1126
1127 if(g_hPipelineLayout != VK_NULL_HANDLE)
1128 {
1129 vkDestroyPipelineLayout(g_hDevice, g_hPipelineLayout, nullptr);
1130 g_hPipelineLayout = VK_NULL_HANDLE;
1131 }
1132
1133 for(size_t i = g_SwapchainImageViews.size(); i--; )
1134 vkDestroyImageView(g_hDevice, g_SwapchainImageViews[i], nullptr);
1135 g_SwapchainImageViews.clear();
1136
1137 if(destroyActualSwapchain && (g_hSwapchain != VK_NULL_HANDLE))
1138 {
1139 vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, nullptr);
1140 g_hSwapchain = VK_NULL_HANDLE;
1141 }
1142}
1143
1144static void InitializeApplication()
1145{
1146 uint32_t instanceLayerPropCount = 0;
1147 ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, nullptr) );
1148 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerPropCount);
1149 if(instanceLayerPropCount > 0)
1150 {
1151 ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, instanceLayerProps.data()) );
1152 }
1153
1154 if(g_EnableValidationLayer == true)
1155 {
1156 if(IsLayerSupported(instanceLayerProps.data(), instanceLayerProps.size(), VALIDATION_LAYER_NAME) == false)
1157 {
1158 printf("Layer \"%s\" not supported.", VALIDATION_LAYER_NAME);
1159 g_EnableValidationLayer = false;
1160 }
1161 }
1162
1163 std::vector<const char*> instanceExtensions;
1164 instanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
1165 instanceExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
1166
1167 std::vector<const char*> instanceLayers;
1168 if(g_EnableValidationLayer == true)
1169 {
1170 instanceLayers.push_back(VALIDATION_LAYER_NAME);
1171 instanceExtensions.push_back("VK_EXT_debug_report");
1172 }
1173
1174 VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
1175 appInfo.pApplicationName = APP_TITLE_A;
1176 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
1177 appInfo.pEngineName = "Adam Sawicki Engine";
1178 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
1179 appInfo.apiVersion = VK_API_VERSION_1_0;
1180
1181 VkInstanceCreateInfo instInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
1182 instInfo.pApplicationInfo = &appInfo;
1183 instInfo.enabledExtensionCount = static_cast<uint32_t>(instanceExtensions.size());
1184 instInfo.ppEnabledExtensionNames = instanceExtensions.data();
1185 instInfo.enabledLayerCount = static_cast<uint32_t>(instanceLayers.size());
1186 instInfo.ppEnabledLayerNames = instanceLayers.data();
1187
1188 ERR_GUARD_VULKAN( vkCreateInstance(&instInfo, NULL, &g_hVulkanInstance) );
1189
1190 // Create VkSurfaceKHR.
1191 VkWin32SurfaceCreateInfoKHR surfaceInfo = { VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR };
1192 surfaceInfo.hinstance = g_hAppInstance;
1193 surfaceInfo.hwnd = g_hWnd;
1194 VkResult result = vkCreateWin32SurfaceKHR(g_hVulkanInstance, &surfaceInfo, NULL, &g_hSurface);
1195 assert(result == VK_SUCCESS);
1196
1197 if(g_EnableValidationLayer == true)
1198 RegisterDebugCallbacks();
1199
1200 // Find physical device
1201
1202 uint32_t deviceCount = 0;
1203 ERR_GUARD_VULKAN( vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, nullptr) );
1204 assert(deviceCount > 0);
1205
1206 std::vector<VkPhysicalDevice> physicalDevices(deviceCount);
1207 ERR_GUARD_VULKAN( vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, physicalDevices.data()) );
1208
1209 g_hPhysicalDevice = physicalDevices[0];
1210
1211 // Query for features
1212
1213 VkPhysicalDeviceProperties physicalDeviceProperties = {};
1214 vkGetPhysicalDeviceProperties(g_hPhysicalDevice, &physicalDeviceProperties);
1215
1216 //VkPhysicalDeviceFeatures physicalDeviceFreatures = {};
1217 //vkGetPhysicalDeviceFeatures(g_PhysicalDevice, &physicalDeviceFreatures);
1218
1219 // Find queue family index
1220
1221 uint32_t queueFamilyCount = 0;
1222 vkGetPhysicalDeviceQueueFamilyProperties(g_hPhysicalDevice, &queueFamilyCount, nullptr);
1223 assert(queueFamilyCount > 0);
1224 std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
1225 vkGetPhysicalDeviceQueueFamilyProperties(g_hPhysicalDevice, &queueFamilyCount, queueFamilies.data());
1226 for(uint32_t i = 0;
1227 (i < queueFamilyCount) &&
1228 (g_GraphicsQueueFamilyIndex == UINT_MAX || g_PresentQueueFamilyIndex == UINT_MAX);
1229 ++i)
1230 {
1231 if(queueFamilies[i].queueCount > 0)
1232 {
1233 if((g_GraphicsQueueFamilyIndex != 0) &&
1234 ((queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0))
1235 {
1236 g_GraphicsQueueFamilyIndex = i;
1237 }
1238
1239 VkBool32 surfaceSupported = 0;
1240 VkResult res = vkGetPhysicalDeviceSurfaceSupportKHR(g_hPhysicalDevice, i, g_hSurface, &surfaceSupported);
1241 if((res >= 0) && (surfaceSupported == VK_TRUE))
1242 {
1243 g_PresentQueueFamilyIndex = i;
1244 }
1245 }
1246 }
1247 assert(g_GraphicsQueueFamilyIndex != UINT_MAX);
1248
1249 // Create logical device
1250
1251 const float queuePriority = 1.f;
1252
1253 VkDeviceQueueCreateInfo deviceQueueCreateInfo[2] = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
1254 deviceQueueCreateInfo[0].queueFamilyIndex = g_GraphicsQueueFamilyIndex;
1255 deviceQueueCreateInfo[0].queueCount = 1;
1256 deviceQueueCreateInfo[0].pQueuePriorities = &queuePriority;
1257 deviceQueueCreateInfo[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
1258 deviceQueueCreateInfo[1].queueFamilyIndex = g_PresentQueueFamilyIndex;
1259 deviceQueueCreateInfo[1].queueCount = 1;
1260 deviceQueueCreateInfo[1].pQueuePriorities = &queuePriority;
1261
1262 VkPhysicalDeviceFeatures deviceFeatures = {};
1263 deviceFeatures.fillModeNonSolid = VK_TRUE;
1264 deviceFeatures.samplerAnisotropy = VK_TRUE;
1265
1266 std::vector<const char*> enabledDeviceExtensions;
1267 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
1268
1269 VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
1270 deviceCreateInfo.enabledLayerCount = 0;
1271 deviceCreateInfo.ppEnabledLayerNames = nullptr;
1272 deviceCreateInfo.enabledExtensionCount = (uint32_t)enabledDeviceExtensions.size();
1273 deviceCreateInfo.ppEnabledExtensionNames = enabledDeviceExtensions.data();
1274 deviceCreateInfo.queueCreateInfoCount = g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex ? 2 : 1;
1275 deviceCreateInfo.pQueueCreateInfos = deviceQueueCreateInfo;
1276 deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
1277
1278 ERR_GUARD_VULKAN( vkCreateDevice(g_hPhysicalDevice, &deviceCreateInfo, nullptr, &g_hDevice) );
1279
1280 // Create memory allocator
1281
1282 VmaAllocatorCreateInfo allocatorInfo = {};
1283 allocatorInfo.physicalDevice = g_hPhysicalDevice;
1284 allocatorInfo.device = g_hDevice;
1285 ERR_GUARD_VULKAN( vmaCreateAllocator(&allocatorInfo, &g_hAllocator) );
1286
1287 // Retrieve queue (doesn't need to be destroyed)
1288
1289 vkGetDeviceQueue(g_hDevice, g_GraphicsQueueFamilyIndex, 0, &g_hGraphicsQueue);
1290 vkGetDeviceQueue(g_hDevice, g_PresentQueueFamilyIndex, 0, &g_hPresentQueue);
1291 assert(g_hGraphicsQueue);
1292 assert(g_hPresentQueue);
1293
1294 // Create command pool
1295
1296 VkCommandPoolCreateInfo commandPoolInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
1297 commandPoolInfo.queueFamilyIndex = g_GraphicsQueueFamilyIndex;
1298 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1299 ERR_GUARD_VULKAN( vkCreateCommandPool(g_hDevice, &commandPoolInfo, nullptr, &g_hCommandPool) );
1300
1301 VkCommandBufferAllocateInfo commandBufferInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
1302 commandBufferInfo.commandPool = g_hCommandPool;
1303 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1304 commandBufferInfo.commandBufferCount = COMMAND_BUFFER_COUNT;
1305 ERR_GUARD_VULKAN( vkAllocateCommandBuffers(g_hDevice, &commandBufferInfo, g_MainCommandBuffers) );
1306
1307 VkFenceCreateInfo fenceInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
1308 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1309 for(size_t i = 0; i < COMMAND_BUFFER_COUNT; ++i)
1310 {
1311 ERR_GUARD_VULKAN( vkCreateFence(g_hDevice, &fenceInfo, nullptr, &g_MainCommandBufferExecutedFances[i]) );
1312 }
1313
1314 commandBufferInfo.commandBufferCount = 1;
1315 ERR_GUARD_VULKAN( vkAllocateCommandBuffers(g_hDevice, &commandBufferInfo, &g_hTemporaryCommandBuffer) );
1316
1317 // Create texture sampler
1318
1319 VkSamplerCreateInfo samplerInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
1320 samplerInfo.magFilter = VK_FILTER_LINEAR;
1321 samplerInfo.minFilter = VK_FILTER_LINEAR;
1322 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1323 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1324 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1325 samplerInfo.anisotropyEnable = VK_TRUE;
1326 samplerInfo.maxAnisotropy = 16;
1327 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
1328 samplerInfo.unnormalizedCoordinates = VK_FALSE;
1329 samplerInfo.compareEnable = VK_FALSE;
1330 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
1331 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1332 samplerInfo.mipLodBias = 0.f;
1333 samplerInfo.minLod = 0.f;
1334 samplerInfo.maxLod = FLT_MAX;
1335 ERR_GUARD_VULKAN( vkCreateSampler(g_hDevice, &samplerInfo, nullptr, &g_hSampler) );
1336
1337 CreateTexture(128, 128);
1338 CreateMesh();
1339
1340 VkDescriptorSetLayoutBinding samplerLayoutBinding = {};
1341 samplerLayoutBinding.binding = 1;
1342 samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1343 samplerLayoutBinding.descriptorCount = 1;
1344 samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
1345
1346 VkDescriptorSetLayoutCreateInfo descriptorSetLayoutInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
1347 descriptorSetLayoutInfo.bindingCount = 1;
1348 descriptorSetLayoutInfo.pBindings = &samplerLayoutBinding;
1349 ERR_GUARD_VULKAN( vkCreateDescriptorSetLayout(g_hDevice, &descriptorSetLayoutInfo, nullptr, &g_hDescriptorSetLayout) );
1350
1351 // Create descriptor pool
1352
1353 VkDescriptorPoolSize descriptorPoolSizes[2];
1354 ZeroMemory(descriptorPoolSizes, sizeof(descriptorPoolSizes));
1355 descriptorPoolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
1356 descriptorPoolSizes[0].descriptorCount = 1;
1357 descriptorPoolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1358 descriptorPoolSizes[1].descriptorCount = 1;
1359
1360 VkDescriptorPoolCreateInfo descriptorPoolInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
1361 descriptorPoolInfo.poolSizeCount = (uint32_t)_countof(descriptorPoolSizes);
1362 descriptorPoolInfo.pPoolSizes = descriptorPoolSizes;
1363 descriptorPoolInfo.maxSets = 1;
1364 ERR_GUARD_VULKAN( vkCreateDescriptorPool(g_hDevice, &descriptorPoolInfo, nullptr, &g_hDescriptorPool) );
1365
1366 // Create descriptor set layout
1367
1368 VkDescriptorSetLayout descriptorSetLayouts[] = { g_hDescriptorSetLayout };
1369 VkDescriptorSetAllocateInfo descriptorSetInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
1370 descriptorSetInfo.descriptorPool = g_hDescriptorPool;
1371 descriptorSetInfo.descriptorSetCount = 1;
1372 descriptorSetInfo.pSetLayouts = descriptorSetLayouts;
1373 ERR_GUARD_VULKAN( vkAllocateDescriptorSets(g_hDevice, &descriptorSetInfo, &g_hDescriptorSet) );
1374
1375 VkDescriptorImageInfo descriptorImageInfo = {};
1376 descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1377 descriptorImageInfo.imageView = g_hTextureImageView;
1378 descriptorImageInfo.sampler = g_hSampler;
1379
1380 VkWriteDescriptorSet writeDescriptorSet = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
1381 writeDescriptorSet.dstSet = g_hDescriptorSet;
1382 writeDescriptorSet.dstBinding = 1;
1383 writeDescriptorSet.dstArrayElement = 0;
1384 writeDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1385 writeDescriptorSet.descriptorCount = 1;
1386 writeDescriptorSet.pImageInfo = &descriptorImageInfo;
1387
1388 vkUpdateDescriptorSets(g_hDevice, 1, &writeDescriptorSet, 0, nullptr);
1389
1390 CreateSwapchain();
1391}
1392
1393static void FinalizeApplication()
1394{
1395 vkDeviceWaitIdle(g_hDevice);
1396
1397 DestroySwapchain(true);
1398
1399 if(g_hDescriptorPool != VK_NULL_HANDLE)
1400 {
1401 vkDestroyDescriptorPool(g_hDevice, g_hDescriptorPool, nullptr);
1402 g_hDescriptorPool = VK_NULL_HANDLE;
1403 }
1404
1405 if(g_hDescriptorSetLayout != VK_NULL_HANDLE)
1406 {
1407 vkDestroyDescriptorSetLayout(g_hDevice, g_hDescriptorSetLayout, nullptr);
1408 g_hDescriptorSetLayout = VK_NULL_HANDLE;
1409 }
1410
1411 if(g_hTextureImageView != VK_NULL_HANDLE)
1412 {
1413 vkDestroyImageView(g_hDevice, g_hTextureImageView, nullptr);
1414 g_hTextureImageView = VK_NULL_HANDLE;
1415 }
1416 if(g_hTextureImage != VK_NULL_HANDLE)
1417 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001418 vmaDestroyImage(g_hAllocator, g_hTextureImage, g_hTextureImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001419 g_hTextureImage = VK_NULL_HANDLE;
1420 }
1421
1422 if(g_hIndexBuffer != VK_NULL_HANDLE)
1423 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001424 vmaDestroyBuffer(g_hAllocator, g_hIndexBuffer, g_hIndexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001425 g_hIndexBuffer = VK_NULL_HANDLE;
1426 }
1427 if(g_hVertexBuffer != VK_NULL_HANDLE)
1428 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001429 vmaDestroyBuffer(g_hAllocator, g_hVertexBuffer, g_hVertexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001430 g_hVertexBuffer = VK_NULL_HANDLE;
1431 }
1432
1433 if(g_hSampler != VK_NULL_HANDLE)
1434 {
1435 vkDestroySampler(g_hDevice, g_hSampler, nullptr);
1436 g_hSampler = VK_NULL_HANDLE;
1437 }
1438
1439 for(size_t i = COMMAND_BUFFER_COUNT; i--; )
1440 {
1441 if(g_MainCommandBufferExecutedFances[i] != VK_NULL_HANDLE)
1442 {
1443 vkDestroyFence(g_hDevice, g_MainCommandBufferExecutedFances[i], nullptr);
1444 g_MainCommandBufferExecutedFances[i] = VK_NULL_HANDLE;
1445 }
1446 }
1447 if(g_MainCommandBuffers[0] != VK_NULL_HANDLE)
1448 {
1449 vkFreeCommandBuffers(g_hDevice, g_hCommandPool, COMMAND_BUFFER_COUNT, g_MainCommandBuffers);
1450 ZeroMemory(g_MainCommandBuffers, sizeof(g_MainCommandBuffers));
1451 }
1452 if(g_hTemporaryCommandBuffer != VK_NULL_HANDLE)
1453 {
1454 vkFreeCommandBuffers(g_hDevice, g_hCommandPool, 1, &g_hTemporaryCommandBuffer);
1455 g_hTemporaryCommandBuffer = VK_NULL_HANDLE;
1456 }
1457
1458 if(g_hCommandPool != VK_NULL_HANDLE)
1459 {
1460 vkDestroyCommandPool(g_hDevice, g_hCommandPool, nullptr);
1461 g_hCommandPool = VK_NULL_HANDLE;
1462 }
1463
1464 if(g_hAllocator != VK_NULL_HANDLE)
1465 {
1466 vmaDestroyAllocator(g_hAllocator);
1467 g_hAllocator = nullptr;
1468 }
1469
1470 if(g_hDevice != VK_NULL_HANDLE)
1471 {
1472 vkDestroyDevice(g_hDevice, nullptr);
1473 g_hDevice = nullptr;
1474 }
1475
1476 if(g_pvkDestroyDebugReportCallbackEXT && g_hCallback != VK_NULL_HANDLE)
1477 {
1478 g_pvkDestroyDebugReportCallbackEXT(g_hVulkanInstance, g_hCallback, nullptr);
1479 g_hCallback = VK_NULL_HANDLE;
1480 }
1481
1482 if(g_hSurface != VK_NULL_HANDLE)
1483 {
1484 vkDestroySurfaceKHR(g_hVulkanInstance, g_hSurface, NULL);
1485 g_hSurface = VK_NULL_HANDLE;
1486 }
1487
1488 if(g_hVulkanInstance != VK_NULL_HANDLE)
1489 {
1490 vkDestroyInstance(g_hVulkanInstance, NULL);
1491 g_hVulkanInstance = VK_NULL_HANDLE;
1492 }
1493}
1494
1495static void PrintAllocatorStats()
1496{
1497#if VMA_STATS_STRING_ENABLED
1498 char* statsString = nullptr;
1499 vmaBuildStatsString(g_hAllocator, &statsString, true);
1500 printf("%s\n", statsString);
1501 vmaFreeStatsString(g_hAllocator, statsString);
1502#endif
1503}
1504
1505static void RecreateSwapChain()
1506{
1507 vkDeviceWaitIdle(g_hDevice);
1508 DestroySwapchain(false);
1509 CreateSwapchain();
1510}
1511
1512static void DrawFrame()
1513{
1514 // Begin main command buffer
1515 size_t cmdBufIndex = (g_NextCommandBufferIndex++) % COMMAND_BUFFER_COUNT;
1516 VkCommandBuffer hCommandBuffer = g_MainCommandBuffers[cmdBufIndex];
1517 VkFence hCommandBufferExecutedFence = g_MainCommandBufferExecutedFances[cmdBufIndex];
1518
1519 ERR_GUARD_VULKAN( vkWaitForFences(g_hDevice, 1, &hCommandBufferExecutedFence, VK_TRUE, UINT64_MAX) );
1520 ERR_GUARD_VULKAN( vkResetFences(g_hDevice, 1, &hCommandBufferExecutedFence) );
1521
1522 VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
1523 commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1524 ERR_GUARD_VULKAN( vkBeginCommandBuffer(hCommandBuffer, &commandBufferBeginInfo) );
1525
1526 // Acquire swapchain image
1527 uint32_t imageIndex = 0;
1528 VkResult res = vkAcquireNextImageKHR(g_hDevice, g_hSwapchain, UINT64_MAX, g_hImageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex);
1529 if(res == VK_ERROR_OUT_OF_DATE_KHR)
1530 {
1531 RecreateSwapChain();
1532 return;
1533 }
1534 else if(res < 0)
1535 {
1536 ERR_GUARD_VULKAN(res);
1537 }
1538
1539 // Record geometry pass
1540
1541 VkClearValue clearValues[2];
1542 ZeroMemory(clearValues, sizeof(clearValues));
1543 clearValues[0].color.float32[0] = 0.25f;
1544 clearValues[0].color.float32[1] = 0.25f;
1545 clearValues[0].color.float32[2] = 0.5f;
1546 clearValues[0].color.float32[3] = 1.0f;
1547 clearValues[1].depthStencil.depth = 1.0f;
1548
1549 VkRenderPassBeginInfo renderPassBeginInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
1550 renderPassBeginInfo.renderPass = g_hRenderPass;
1551 renderPassBeginInfo.framebuffer = g_Framebuffers[imageIndex];
1552 renderPassBeginInfo.renderArea.offset.x = 0;
1553 renderPassBeginInfo.renderArea.offset.y = 0;
1554 renderPassBeginInfo.renderArea.extent = g_Extent;
1555 renderPassBeginInfo.clearValueCount = (uint32_t)_countof(clearValues);
1556 renderPassBeginInfo.pClearValues = clearValues;
1557 vkCmdBeginRenderPass(hCommandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
1558
1559 vkCmdBindPipeline(
1560 hCommandBuffer,
1561 VK_PIPELINE_BIND_POINT_GRAPHICS,
1562 g_hPipeline);
1563
1564 mathfu::mat4 view = mathfu::mat4::LookAt(
1565 mathfu::kZeros3f,
1566 mathfu::vec3(0.f, -2.f, 4.f),
1567 mathfu::kAxisY3f);
1568 mathfu::mat4 proj = mathfu::mat4::Perspective(
1569 1.0471975511966f, // 60 degrees
1570 (float)g_Extent.width / (float)g_Extent.height,
1571 0.1f,
1572 1000.f,
1573 -1.f);
1574 //proj[1][1] *= -1.f;
1575 mathfu::mat4 viewProj = proj * view;
1576
1577 vkCmdBindDescriptorSets(
1578 hCommandBuffer,
1579 VK_PIPELINE_BIND_POINT_GRAPHICS,
1580 g_hPipelineLayout,
1581 0,
1582 1,
1583 &g_hDescriptorSet,
1584 0,
1585 nullptr);
1586
1587 float rotationAngle = (float)GetTickCount() * 0.001f * (float)M_PI * 0.2f;
1588 mathfu::mat3 model_3 = mathfu::mat3::RotationY(rotationAngle);
1589 mathfu::mat4 model_4 = mathfu::mat4(
1590 model_3(0, 0), model_3(0, 1), model_3(0, 2), 0.f,
1591 model_3(1, 0), model_3(1, 1), model_3(1, 2), 0.f,
1592 model_3(2, 0), model_3(2, 1), model_3(2, 2), 0.f,
1593 0.f, 0.f, 0.f, 1.f);
1594 mathfu::mat4 modelViewProj = viewProj * model_4;
1595
1596 UniformBufferObject ubo = {};
1597 modelViewProj.Pack(ubo.ModelViewProj);
1598 vkCmdPushConstants(hCommandBuffer, g_hPipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(UniformBufferObject), &ubo);
1599
1600 VkBuffer vertexBuffers[] = { g_hVertexBuffer };
1601 VkDeviceSize offsets[] = { 0 };
1602 vkCmdBindVertexBuffers(hCommandBuffer, 0, 1, vertexBuffers, offsets);
1603
1604 vkCmdBindIndexBuffer(hCommandBuffer, g_hIndexBuffer, 0, VK_INDEX_TYPE_UINT16);
1605
1606 vkCmdDrawIndexed(hCommandBuffer, g_IndexCount, 1, 0, 0, 0);
1607
1608 vkCmdEndRenderPass(hCommandBuffer);
1609
1610 vkEndCommandBuffer(hCommandBuffer);
1611
1612 // Submit command buffer
1613
1614 VkSemaphore submitWaitSemaphores[] = { g_hImageAvailableSemaphore };
1615 VkPipelineStageFlags submitWaitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
1616 VkSemaphore submitSignalSemaphores[] = { g_hRenderFinishedSemaphore };
1617 VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
1618 submitInfo.waitSemaphoreCount = 1;
1619 submitInfo.pWaitSemaphores = submitWaitSemaphores;
1620 submitInfo.pWaitDstStageMask = submitWaitStages;
1621 submitInfo.commandBufferCount = 1;
1622 submitInfo.pCommandBuffers = &hCommandBuffer;
1623 submitInfo.signalSemaphoreCount = _countof(submitSignalSemaphores);
1624 submitInfo.pSignalSemaphores = submitSignalSemaphores;
1625 ERR_GUARD_VULKAN( vkQueueSubmit(g_hGraphicsQueue, 1, &submitInfo, hCommandBufferExecutedFence) );
1626
1627 VkSemaphore presentWaitSemaphores[] = { g_hRenderFinishedSemaphore };
1628
1629 VkSwapchainKHR swapchains[] = { g_hSwapchain };
1630 VkPresentInfoKHR presentInfo = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
1631 presentInfo.waitSemaphoreCount = _countof(presentWaitSemaphores);
1632 presentInfo.pWaitSemaphores = presentWaitSemaphores;
1633 presentInfo.swapchainCount = 1;
1634 presentInfo.pSwapchains = swapchains;
1635 presentInfo.pImageIndices = &imageIndex;
1636 presentInfo.pResults = nullptr;
1637 res = vkQueuePresentKHR(g_hPresentQueue, &presentInfo);
1638 if(res == VK_ERROR_OUT_OF_DATE_KHR)
1639 {
1640 RecreateSwapChain();
1641 }
1642 else
1643 ERR_GUARD_VULKAN(res);
1644}
1645
1646static void HandlePossibleSizeChange()
1647{
1648 RECT clientRect;
1649 GetClientRect(g_hWnd, &clientRect);
1650 LONG newSizeX = clientRect.right - clientRect.left;
1651 LONG newSizeY = clientRect.bottom - clientRect.top;
1652 if((newSizeX > 0) &&
1653 (newSizeY > 0) &&
1654 ((newSizeX != g_SizeX) || (newSizeY != g_SizeY)))
1655 {
1656 g_SizeX = newSizeX;
1657 g_SizeY = newSizeY;
1658
1659 RecreateSwapChain();
1660 }
1661}
1662
1663static LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1664{
1665 switch(msg)
1666 {
1667 case WM_CREATE:
1668 // This is intentionally assigned here because we are now inside CreateWindow, before it returns.
1669 g_hWnd = hWnd;
1670 InitializeApplication();
1671 PrintAllocatorStats();
1672 return 0;
1673
1674 case WM_DESTROY:
1675 FinalizeApplication();
1676 PostQuitMessage(0);
1677 return 0;
1678
1679 // This prevents app from freezing when left Alt is pressed
1680 // (which normally enters modal menu loop).
1681 case WM_SYSKEYDOWN:
1682 case WM_SYSKEYUP:
1683 return 0;
1684
1685 case WM_SIZE:
1686 if((wParam == SIZE_MAXIMIZED) || (wParam == SIZE_RESTORED))
1687 HandlePossibleSizeChange();
1688 return 0;
1689
1690 case WM_EXITSIZEMOVE:
1691 HandlePossibleSizeChange();
1692 return 0;
1693
1694 case WM_KEYDOWN:
1695 if(wParam == VK_ESCAPE)
1696 PostMessage(hWnd, WM_CLOSE, 0, 0);
1697 return 0;
1698
1699 default:
1700 break;
1701 }
1702
1703 return DefWindowProc(hWnd, msg, wParam, lParam);
1704}
1705
1706int main()
1707{
1708 g_hAppInstance = (HINSTANCE)GetModuleHandle(NULL);
1709
1710 WNDCLASSEX wndClassDesc = { sizeof(WNDCLASSEX) };
1711 wndClassDesc.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
1712 wndClassDesc.hbrBackground = NULL;
1713 wndClassDesc.hCursor = LoadCursor(NULL, IDC_CROSS);
1714 wndClassDesc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
1715 wndClassDesc.hInstance = g_hAppInstance;
1716 wndClassDesc.lpfnWndProc = WndProc;
1717 wndClassDesc.lpszClassName = WINDOW_CLASS_NAME;
1718
1719 const ATOM hWndClass = RegisterClassEx(&wndClassDesc);
1720 assert(hWndClass);
1721
1722 const DWORD style = WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME;
1723 const DWORD exStyle = 0;
1724
1725 RECT rect = { 0, 0, g_SizeX, g_SizeY };
1726 AdjustWindowRectEx(&rect, style, FALSE, exStyle);
1727
Adam Sawicki86ccd632017-07-04 14:57:53 +02001728 CreateWindowEx(
Adam Sawickie6e498f2017-06-16 17:21:31 +02001729 exStyle, WINDOW_CLASS_NAME, APP_TITLE_W, style,
1730 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
1731 NULL, NULL, g_hAppInstance, NULL);
1732
1733 MSG msg;
1734 for(;;)
1735 {
1736 if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1737 {
1738 if(msg.message == WM_QUIT)
1739 break;
1740 TranslateMessage(&msg);
1741 DispatchMessage(&msg);
1742 }
1743 if(g_hDevice != VK_NULL_HANDLE)
1744 DrawFrame();
1745 }
1746
1747 return 0;
1748}
Adam Sawicki59a3e7e2017-08-21 15:47:30 +02001749
1750#else // #ifdef WIN32
1751
1752#define VMA_IMPLEMENTATION
1753#include "vk_mem_alloc.h"
1754
1755int main()
1756{
1757}
1758
1759#endif // #ifdef WIN32
1760