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