blob: 60cde8a4810c125104d49781982d4cf982b7042f [file] [log] [blame]
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001/*
2* Copyright (c) 2015-2016 The Khronos Group Inc.
3* Copyright (c) 2015-2016 Valve Corporation
4* Copyright (c) 2015-2016 LunarG, Inc.
5*
6* Licensed under the Apache License, Version 2.0 (the "License");
7* you may not use this file except in compliance with the License.
8* You may obtain a copy of the License at
9*
10* http://www.apache.org/licenses/LICENSE-2.0
11*
12* Unless required by applicable law or agreed to in writing, software
13* distributed under the License is distributed on an "AS IS" BASIS,
14* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15* See the License for the specific language governing permissions and
16* limitations under the License.
17*
18* Author: Jeremy Hayes <jeremy@lunarg.com>
19*/
20
21#if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
22#include <X11/Xutil.h>
23#endif
24
25#include <cassert>
26#include <cstdio>
27#include <cstdlib>
28#include <cstring>
29#include <csignal>
30#include <memory>
31
32#define VULKAN_HPP_NO_EXCEPTIONS
33#include <vulkan/vulkan.hpp>
34#include <vulkan/vk_sdk_platform.h>
35
36#include "linmath.h"
37
38#ifndef NDEBUG
39#define VERIFY(x) assert(x)
40#else
41#define VERIFY(x) ((void)(x))
42#endif
43
44#define APP_SHORT_NAME "cube"
45#ifdef _WIN32
46#define APP_NAME_STR_LEN 80
47#endif
48
49// Allow a maximum of two outstanding presentation operations.
50#define FRAME_LAG 2
51
52#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
53
54#ifdef _WIN32
55#define ERR_EXIT(err_msg, err_class) \
56 do { \
57 if (!suppress_popups) \
58 MessageBox(nullptr, err_msg, err_class, MB_OK); \
59 exit(1); \
60 } while (0)
61#else
62#define ERR_EXIT(err_msg, err_class) \
63 do { \
64 printf(err_msg); \
65 fflush(stdout); \
66 exit(1); \
67 } while (0)
68#endif
69
70struct texture_object
71{
72 vk::Sampler sampler;
73
74 vk::Image image;
75 vk::ImageLayout imageLayout;
76
77 vk::MemoryAllocateInfo mem_alloc;
78 vk::DeviceMemory mem;
79 vk::ImageView view;
80
81 int32_t tex_width;
82 int32_t tex_height;
83};
84
85static char const*const tex_files[] = {"lunarg.ppm"};
86
87static int validation_error = 0;
88
89struct vkcube_vs_uniform {
90 // Must start with MVP
91 float mvp[4][4];
92 float position[12 * 3][4];
93 float color[12 * 3][4];
94};
95
96struct vktexcube_vs_uniform {
97 // Must start with MVP
98 float mvp[4][4];
99 float position[12 * 3][4];
100 float attr[12 * 3][4];
101};
102
103//--------------------------------------------------------------------------------------
104// Mesh and VertexFormat Data
105//--------------------------------------------------------------------------------------
106// clang-format off
107static const float g_vertex_buffer_data[] = {
108 -1.0f,-1.0f,-1.0f, // -X side
109 -1.0f,-1.0f, 1.0f,
110 -1.0f, 1.0f, 1.0f,
111 -1.0f, 1.0f, 1.0f,
112 -1.0f, 1.0f,-1.0f,
113 -1.0f,-1.0f,-1.0f,
114
115 -1.0f,-1.0f,-1.0f, // -Z side
116 1.0f, 1.0f,-1.0f,
117 1.0f,-1.0f,-1.0f,
118 -1.0f,-1.0f,-1.0f,
119 -1.0f, 1.0f,-1.0f,
120 1.0f, 1.0f,-1.0f,
121
122 -1.0f,-1.0f,-1.0f, // -Y side
123 1.0f,-1.0f,-1.0f,
124 1.0f,-1.0f, 1.0f,
125 -1.0f,-1.0f,-1.0f,
126 1.0f,-1.0f, 1.0f,
127 -1.0f,-1.0f, 1.0f,
128
129 -1.0f, 1.0f,-1.0f, // +Y side
130 -1.0f, 1.0f, 1.0f,
131 1.0f, 1.0f, 1.0f,
132 -1.0f, 1.0f,-1.0f,
133 1.0f, 1.0f, 1.0f,
134 1.0f, 1.0f,-1.0f,
135
136 1.0f, 1.0f,-1.0f, // +X side
137 1.0f, 1.0f, 1.0f,
138 1.0f,-1.0f, 1.0f,
139 1.0f,-1.0f, 1.0f,
140 1.0f,-1.0f,-1.0f,
141 1.0f, 1.0f,-1.0f,
142
143 -1.0f, 1.0f, 1.0f, // +Z side
144 -1.0f,-1.0f, 1.0f,
145 1.0f, 1.0f, 1.0f,
146 -1.0f,-1.0f, 1.0f,
147 1.0f,-1.0f, 1.0f,
148 1.0f, 1.0f, 1.0f,
149};
150
151static const float g_uv_buffer_data[] = {
152 0.0f, 1.0f, // -X side
153 1.0f, 1.0f,
154 1.0f, 0.0f,
155 1.0f, 0.0f,
156 0.0f, 0.0f,
157 0.0f, 1.0f,
158
159 1.0f, 1.0f, // -Z side
160 0.0f, 0.0f,
161 0.0f, 1.0f,
162 1.0f, 1.0f,
163 1.0f, 0.0f,
164 0.0f, 0.0f,
165
166 1.0f, 0.0f, // -Y side
167 1.0f, 1.0f,
168 0.0f, 1.0f,
169 1.0f, 0.0f,
170 0.0f, 1.0f,
171 0.0f, 0.0f,
172
173 1.0f, 0.0f, // +Y side
174 0.0f, 0.0f,
175 0.0f, 1.0f,
176 1.0f, 0.0f,
177 0.0f, 1.0f,
178 1.0f, 1.0f,
179
180 1.0f, 0.0f, // +X side
181 0.0f, 0.0f,
182 0.0f, 1.0f,
183 0.0f, 1.0f,
184 1.0f, 1.0f,
185 1.0f, 0.0f,
186
187 0.0f, 0.0f, // +Z side
188 0.0f, 1.0f,
189 1.0f, 0.0f,
190 0.0f, 1.0f,
191 1.0f, 1.0f,
192 1.0f, 0.0f,
193};
194
195typedef struct
196{
197 vk::Image image;
198 vk::CommandBuffer cmd;
199 vk::CommandBuffer graphics_to_present_cmd;
200 vk::ImageView view;
201} SwapchainBuffers;
202
203#ifdef _WIN32
204// MS-Windows event handling function:
205LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
206#endif
207
208struct Demo
209{
210 Demo() :
211#if defined(VK_USE_PLATFORM_WIN32_KHR)
212 connection{nullptr},
213 window{nullptr},
214 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
215#elif defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
216 display{nullptr},
217 xlib_window{0},
218 xlib_wm_delete_window{0},
219 connection{nullptr},
220 screen{nullptr},
221 xcb_window{0},
222 atom_wm_delete_window{nullptr},
223#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
224 display{nullptr},
225 registry{nullptr},
226 compositor{nullptr},
227 window{nullptr},
228 shell{nullptr},
229 shell_surface{nullptr},
230#endif
231 prepared{false},
232 use_staging_buffer{false},
233 use_xlib{false},
234 graphics_queue_family_index{0},
235 present_queue_family_index{0},
236 enabled_extension_count{0},
237 enabled_layer_count{0},
238 width{0},
239 height{0},
240 swapchainImageCount{0},
241 frame_index{0},
242 spin_angle{0.0f},
243 spin_increment{0.0f},
244 pause{false},
245 quit{false},
246 curFrame{0},
247 frameCount{0},
248 validate{false},
249 use_break{false},
250 suppress_popups{false},
251 current_buffer{0},
252 queue_family_count{0}
253 {
254#if defined(VK_USE_PLATFORM_WIN32_KHR)
255 memset(name, '\0', APP_NAME_STR_LEN);
256#elif defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
257#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
258#endif
259 memset(fencesInited, 0, sizeof(bool)*FRAME_LAG);
260 memset(projection_matrix, 0, sizeof(projection_matrix));
261 memset(view_matrix, 0, sizeof(view_matrix));
262 memset(model_matrix, 0, sizeof(model_matrix));
263 }
264
265 void build_image_ownership_cmd(uint32_t const& i)
266 {
267 auto const cmd_buf_info = vk::CommandBufferBeginInfo()
268 .setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
269 auto result = buffers[i].graphics_to_present_cmd.begin(&cmd_buf_info);
270 VERIFY(result == vk::Result::eSuccess);
271
272 auto const image_ownership_barrier = vk::ImageMemoryBarrier()
273 .setSrcAccessMask(vk::AccessFlags())
274 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
275 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
276 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
277 .setSrcQueueFamilyIndex(graphics_queue_family_index)
278 .setDstQueueFamilyIndex(present_queue_family_index)
279 .setImage(buffers[i].image)
280 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
281
282 buffers[i].graphics_to_present_cmd.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput,
283 vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1,
284 &image_ownership_barrier);
285
286 result = buffers[i].graphics_to_present_cmd.end();
287 VERIFY(result == vk::Result::eSuccess);
288 }
289
290 vk::Bool32 check_layers(uint32_t check_count, char const*const*const check_names, uint32_t layer_count,
291 vk::LayerProperties *layers)
292 {
293 for(uint32_t i = 0; i < check_count; i++)
294 {
295 vk::Bool32 found = VK_FALSE;
296 for(uint32_t j = 0; j < layer_count; j++)
297 {
298 if(!strcmp(check_names[i], layers[j].layerName))
299 {
300 found = VK_TRUE;
301 break;
302 }
303 }
304 if(!found)
305 {
306 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
307 return 0;
308 }
309 }
310 return VK_TRUE;
311 }
312
313 void cleanup()
314 {
315 prepared = false;
316 device.waitIdle();
317
318 // Wait for fences from present operations
319 for(uint32_t i = 0; i < FRAME_LAG; i++)
320 {
321 if(fencesInited[i])
322 {
323 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
324 }
325 device.destroyFence(fences[i], nullptr);
326 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
327 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
328 if(separate_present_queue)
329 {
330 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
331 }
332 }
333
334 for(uint32_t i = 0; i < swapchainImageCount; i++)
335 {
336 device.destroyFramebuffer(framebuffers[i], nullptr);
337 }
338 device.destroyDescriptorPool(desc_pool, nullptr);
339
340 device.destroyPipeline(pipeline, nullptr);
341 device.destroyPipelineCache(pipelineCache, nullptr);
342 device.destroyRenderPass(render_pass, nullptr);
343 device.destroyPipelineLayout(pipeline_layout, nullptr);
344 device.destroyDescriptorSetLayout(desc_layout, nullptr);
345
346 for(uint32_t i = 0; i < texture_count; i++)
347 {
348 device.destroyImageView(textures[i].view, nullptr);
349 device.destroyImage(textures[i].image, nullptr);
350 device.freeMemory(textures[i].mem, nullptr);
351 device.destroySampler(textures[i].sampler, nullptr);
352 }
353 device.destroySwapchainKHR(swapchain, nullptr);
354
355 device.destroyImageView(depth.view, nullptr);
356 device.destroyImage(depth.image, nullptr);
357 device.freeMemory(depth.mem, nullptr);
358
359 device.destroyBuffer(uniform_data.buf, nullptr);
360 device.freeMemory(uniform_data.mem, nullptr);
361
362 for(uint32_t i = 0; i < swapchainImageCount; i++)
363 {
364 device.destroyImageView(buffers[i].view, nullptr);
365 device.freeCommandBuffers(cmd_pool, 1, &buffers[i].cmd);
366 }
367
368 device.destroyCommandPool(cmd_pool, nullptr);
369
370 if(separate_present_queue)
371 {
372 device.destroyCommandPool(present_cmd_pool, nullptr);
373 }
374
375 device.destroy(nullptr);
376 inst.destroySurfaceKHR(surface, nullptr);
377 inst.destroy(nullptr);
378
379#if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
380 if(use_xlib)
381 {
382 XDestroyWindow(display, xlib_window);
383 XCloseDisplay(display);
384 }
385 else
386 {
387 xcb_destroy_window(connection, xcb_window);
388 xcb_disconnect(connection);
389 }
390 free(atom_wm_delete_window);
391#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
392 wl_shell_surface_destroy(shell_surface);
393 wl_surface_destroy(window);
394 wl_shell_destroy(shell);
395 wl_compositor_destroy(compositor);
396 wl_registry_destroy(registry);
397 wl_display_disconnect(display);
398#endif
399 }
400
401 void create_device()
402 {
403 float const priorities[1] = {0.0};
404
405 vk::DeviceQueueCreateInfo queues[2];
406 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
407 queues[0].setQueueCount(1);
408 queues[0].setPQueuePriorities(priorities);
409
410 auto deviceInfo = vk::DeviceCreateInfo()
411 .setQueueCreateInfoCount(1)
412 .setPQueueCreateInfos(queues)
413 .setEnabledLayerCount(0)
414 .setPpEnabledLayerNames(nullptr)
415 .setEnabledExtensionCount(enabled_extension_count)
416 .setPpEnabledExtensionNames((const char *const *)extension_names)
417 .setPEnabledFeatures(nullptr);
418
419 if(separate_present_queue)
420 {
421 queues[1].setQueueFamilyIndex(present_queue_family_index);
422 queues[1].setQueueCount(1);
423 queues[1].setPQueuePriorities(priorities);
424 deviceInfo.setQueueCreateInfoCount(2);
425 }
426
427 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
428 VERIFY(result == vk::Result::eSuccess);
429 }
430
431 void destroy_texture_image(texture_object *tex_objs)
432 {
433 // clean up staging resources
434 device.freeMemory(tex_objs->mem, nullptr);
435 device.destroyImage(tex_objs->image, nullptr);
436 }
437
438 void draw()
439 {
440 if(fencesInited[frame_index])
441 {
442 // Ensure no more than FRAME_LAG presentations are outstanding
443 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
444 device.resetFences(1, &fences[frame_index]);
445 }
446
447 // Get the index of the next available swapchain image:
448 auto result = device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], fences[frame_index],
449 &current_buffer);
450 fencesInited[frame_index] = true;
451 if(result == vk::Result::eErrorOutOfDateKHR)
452 {
453 // swapchain is out of date (e.g. the window was resized) and
454 // must be recreated:
455 frame_index += 1;
456 frame_index %= FRAME_LAG;
457
458 resize();
459 draw();
460 return;
461 }
462 else if(result == vk::Result::eSuboptimalKHR)
463 {
464 // swapchain is not as optimal as it could be, but the platform's
465 // presentation engine will still present the image correctly.
466 }
467 else
468 {
469 VERIFY(result == vk::Result::eSuccess);
470 }
471
472 // Wait for the image acquired semaphore to be signaled to ensure
473 // that the image won't be rendered to until the presentation
474 // engine has fully released ownership to the application, and it is
475 // okay to render to the image.
476 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
477 auto const submit_info = vk::SubmitInfo()
478 .setPWaitDstStageMask(&pipe_stage_flags)
479 .setWaitSemaphoreCount(1)
480 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
481 .setCommandBufferCount(1)
482 .setPCommandBuffers(&buffers[current_buffer].cmd)
483 .setSignalSemaphoreCount(1)
484 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
485
486 result = graphics_queue.submit(1, &submit_info, vk::Fence());
487 VERIFY(result == vk::Result::eSuccess);
488
489 if(separate_present_queue)
490 {
491 // If we are using separate queues, change image ownership to the
492 // present queue before presenting, waiting for the draw complete
493 // semaphore and signalling the ownership released semaphore when finished
494 auto const submit_info = vk::SubmitInfo()
495 .setPWaitDstStageMask(&pipe_stage_flags)
496 .setWaitSemaphoreCount(1)
497 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
498 .setCommandBufferCount(1)
499 .setPCommandBuffers(&buffers[current_buffer].graphics_to_present_cmd)
500 .setSignalSemaphoreCount(1)
501 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
502
503 result = present_queue.submit(1, &submit_info, vk::Fence());
504 VERIFY(result == vk::Result::eSuccess);
505 }
506
507 // If we are using separate queues we have to wait for image ownership,
508 // otherwise wait for draw complete
509 auto const presentInfo = vk::PresentInfoKHR()
510 .setWaitSemaphoreCount(1)
511 .setPWaitSemaphores(separate_present_queue ?
512 &image_ownership_semaphores[frame_index] : &draw_complete_semaphores[frame_index])
513 .setSwapchainCount(1)
514 .setPSwapchains(&swapchain)
515 .setPImageIndices(&current_buffer);
516
517 result = present_queue.presentKHR(&presentInfo);
518 frame_index += 1;
519 frame_index %= FRAME_LAG;
520 if(result == vk::Result::eErrorOutOfDateKHR)
521 {
522 // swapchain is out of date (e.g. the window was resized) and
523 // must be recreated:
524 resize();
525 }
526 else if(result == vk::Result::eSuboptimalKHR)
527 {
528 // swapchain is not as optimal as it could be, but the platform's
529 // presentation engine will still present the image correctly.
530 }
531 else
532 {
533 VERIFY(result == vk::Result::eSuccess);
534 }
535 }
536
537 void draw_build_cmd(vk::CommandBuffer commandBuffer)
538 {
539 auto const commandInfo = vk::CommandBufferBeginInfo()
540 .setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
541
542 vk::ClearValue const clearValues[2] =
543 {
544 vk::ClearColorValue(std::array<float, 4>({ 0.2f, 0.2f, 0.2f, 0.2f })),
545 vk::ClearDepthStencilValue(1.0f, 0u)
546 };
547
548 auto const passInfo = vk::RenderPassBeginInfo()
549 .setRenderPass(render_pass)
550 .setFramebuffer(framebuffers[current_buffer])
551 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
552 .setClearValueCount(2)
553 .setPClearValues(clearValues);
554
555 auto result = commandBuffer.begin(&commandInfo);
556 VERIFY(result == vk::Result::eSuccess);
557
558 auto const image_memory_barrier = vk::ImageMemoryBarrier()
559 .setSrcAccessMask(vk::AccessFlagBits::eMemoryRead)
560 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
561 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
562 .setNewLayout(vk::ImageLayout::eColorAttachmentOptimal)
563 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
564 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
565 .setImage(buffers[current_buffer].image)
566 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
567
568 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput,
569 vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1,
570 &image_memory_barrier);
571
572 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
573
574 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
575 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout,
576 0, 1, &desc_set,
577 0, nullptr);
578
579 auto const viewport = vk::Viewport()
580 .setWidth((float)width)
581 .setHeight((float)height)
582 .setMinDepth((float)0.0f)
583 .setMaxDepth((float)1.0f);
584 commandBuffer.setViewport(0, 1, &viewport);
585
586 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
587 commandBuffer.setScissor(0, 1, &scissor);
588 commandBuffer.draw(12 * 3, 1, 0, 0);
589 // Note that ending the renderpass changes the image's layout from
590 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
591 commandBuffer.endRenderPass();
592
593 if(separate_present_queue)
594 {
595 // We have to transfer ownership from the graphics queue family to the
596 // present queue family to be able to present. Note that we don't have
597 // to transfer from present queue family back to graphics queue family at
598 // the start of the next frame because we don't care about the image's
599 // contents at that point.
600 auto const image_ownership_barrier = vk::ImageMemoryBarrier()
601 .setSrcAccessMask(vk::AccessFlags())
602 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
603 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
604 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
605 .setSrcQueueFamilyIndex(graphics_queue_family_index)
606 .setDstQueueFamilyIndex(present_queue_family_index)
607 .setImage(buffers[current_buffer].image)
608 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
609
610 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput,
611 vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1,
612 &image_ownership_barrier);
613 }
614
615 result = commandBuffer.end();
616 VERIFY(result == vk::Result::eSuccess);
617 }
618
619 void flush_init_cmd()
620 {
621 // TODO: hmm.
622 // This function could get called twice if the texture uses a staging buffer
623 // In that case the second call should be ignored
624 if(!cmd)
625 {
626 return;
627 }
628
629 auto result = cmd.end();
630 VERIFY(result == vk::Result::eSuccess);
631
632 auto const fenceInfo = vk::FenceCreateInfo()
633 .setFlags(vk::FenceCreateFlagBits(0));
634 vk::Fence fence;
635 device.createFence(&fenceInfo, nullptr, &fence);
636
637 vk::CommandBuffer const commandBuffers[] =
638 {
639 cmd
640 };
641 auto const submitInfo = vk::SubmitInfo()
642 .setCommandBufferCount(1)
643 .setPCommandBuffers(commandBuffers);
644
645 result = graphics_queue.submit(1, &submitInfo, fence);
646 VERIFY(result == vk::Result::eSuccess);
647
648 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
649 VERIFY(result == vk::Result::eSuccess);
650
651 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
652 device.destroyFence(fence, nullptr);
653
654 cmd = vk::CommandBuffer();
655 }
656
657 void init(int argc, char **argv)
658 {
659 vec3 eye = {0.0f, 3.0f, 5.0f};
660 vec3 origin = {0, 0, 0};
661 vec3 up = {0.0f, 1.0f, 0.0};
662
663 frameCount = UINT32_MAX;
664 use_xlib = false;
665
666 for (int i = 1; i < argc; i++) {
667 if(strcmp(argv[i], "--use_staging") == 0)
668 {
669 use_staging_buffer = true;
670 continue;
671 }
672 if(strcmp(argv[i], "--break") == 0)
673 {
674 use_break = true;
675 continue;
676 }
677 if(strcmp(argv[i], "--validate") == 0)
678 {
679 validate = true;
680 continue;
681 }
682#if defined(VK_USE_PLATFORM_XLIB_KHR)
683 if(strcmp(argv[i], "--xlib") == 0)
684 {
685 use_xlib = true;
686 continue;
687 }
688#endif
689 if(strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX &&
690 i < argc - 1 && sscanf(argv[i + 1], "%d", &frameCount) == 1)
691 {
692 i++;
693 continue;
694 }
695 if(strcmp(argv[i], "--suppress_popups") == 0)
696 {
697 suppress_popups = true;
698 continue;
699 }
700
701 fprintf(stderr, "Usage:\n %s [--use_staging] [--validate] [--break] "
702#if defined(VK_USE_PLATFORM_XLIB_KHR)
703 "[--xlib] "
704#endif
705 "[--c <framecount>] [--suppress_popups]\n",
706 APP_SHORT_NAME);
707 fflush(stderr);
708 exit(1);
709 }
710
711 if(!use_xlib)
712 {
713 init_connection();
714 }
715
716 init_vk();
717
718 width = 500;
719 height = 500;
720
721 spin_angle = 4.0f;
722 spin_increment = 0.2f;
723 pause = false;
724
725 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f),
726 1.0f, 0.1f, 100.0f);
727 mat4x4_look_at(view_matrix, eye, origin, up);
728 mat4x4_identity(model_matrix);
729
730 projection_matrix[1][1]*=-1; //Flip projection matrix from GL to Vulkan orientation.
731 }
732
733 void init_connection()
734 {
735#if defined(VK_USE_PLATFORM_XCB_KHR)
736 const xcb_setup_t *setup;
737 xcb_screen_iterator_t iter;
738 int scr;
739
740 connection = xcb_connect(nullptr, &scr);
741 if(xcb_connection_has_error(connection) > 0)
742 {
743 printf("Cannot find a compatible Vulkan installable client driver "
744 "(ICD).\nExiting ...\n");
745 fflush(stdout);
746 exit(1);
747 }
748
749 setup = xcb_get_setup(connection);
750 iter = xcb_setup_roots_iterator(setup);
751 while(scr-- > 0)
752 xcb_screen_next(&iter);
753
754 screen = iter.data;
755#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
756 display = wl_display_connect(nullptr);
757
758 if(display == nullptr)
759 {
760 printf("Cannot find a compatible Vulkan installable client driver "
761 "(ICD).\nExiting ...\n");
762 fflush(stdout);
763 exit(1);
764 }
765
766 registry = wl_display_get_registry(display);
767 wl_registry_add_listener(registry, &registry_listener, this);
768 wl_display_dispatch(display);
769#endif
770 }
771
772 void init_vk()
773 {
774 uint32_t instance_extension_count = 0;
775 uint32_t instance_layer_count = 0;
776 uint32_t validation_layer_count = 0;
777 char const*const* instance_validation_layers = nullptr;
778 enabled_extension_count = 0;
779 enabled_layer_count = 0;
780
781 char const*const instance_validation_layers_alt1[] =
782 {
783 "VK_LAYER_LUNARG_standard_validation"
784 };
785
786 char const*const instance_validation_layers_alt2[] =
787 {
788 "VK_LAYER_GOOGLE_threading",
789 "VK_LAYER_LUNARG_parameter_validation",
790 "VK_LAYER_LUNARG_object_tracker",
791 "VK_LAYER_LUNARG_image",
792 "VK_LAYER_LUNARG_core_validation",
793 "VK_LAYER_LUNARG_swapchain",
794 "VK_LAYER_GOOGLE_unique_objects"
795 };
796
797 // Look for validation layers
798 vk::Bool32 validation_found = VK_FALSE;
799 if(validate)
800 {
801 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, nullptr);
802 VERIFY(result == vk::Result::eSuccess);
803
804 instance_validation_layers = instance_validation_layers_alt1;
805 if(instance_layer_count > 0)
806 {
807 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
808 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
809 VERIFY(result == vk::Result::eSuccess);
810
811 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers,
812 instance_layer_count, instance_layers.get());
813 if(validation_found)
814 {
815 enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
816 enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation";
817 validation_layer_count = 1;
818 }
819 else
820 {
821 // use alternative set of validation layers
822 instance_validation_layers = instance_validation_layers_alt2;
823 enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
824 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers,
825 instance_layer_count, instance_layers.get());
826 validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
827 for (uint32_t i = 0; i < validation_layer_count; i++)
828 {
829 enabled_layers[i] = instance_validation_layers[i];
830 }
831 }
832 }
833
834 if(!validation_found)
835 {
836 ERR_EXIT("vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
837 "Please look at the Getting Started guide for additional information.\n",
838 "vkCreateInstance Failure");
839 }
840 }
841
842 /* Look for instance extensions */
843 vk::Bool32 surfaceExtFound = VK_FALSE;
844 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
845#if defined(VK_USE_PLATFORM_XLIB_KHR)
846 vk::Bool32 xlibSurfaceExtFound = VK_FALSE;
847#endif
848 memset(extension_names, 0, sizeof(extension_names));
849
850 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
851 VERIFY(result == vk::Result::eSuccess);
852
853 if(instance_extension_count > 0)
854 {
855 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
856 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
857 VERIFY(result == vk::Result::eSuccess);
858
859 for(uint32_t i = 0; i < instance_extension_count; i++)
860 {
861 if(!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName))
862 {
863 surfaceExtFound = 1;
864 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
865 }
866#if defined(VK_USE_PLATFORM_WIN32_KHR)
867 if(!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName))
868 {
869 platformSurfaceExtFound = 1;
870 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
871 }
872#endif
873#if defined(VK_USE_PLATFORM_XLIB_KHR)
874 if(!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName))
875 {
876 platformSurfaceExtFound = 1;
877 xlibSurfaceExtFound = 1;
878 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
879 }
880#endif
881#if defined(VK_USE_PLATFORM_XCB_KHR)
882 if(!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName))
883 {
884 platformSurfaceExtFound = 1;
885 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
886 }
887#endif
888#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
889 if(!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName))
890 {
891 platformSurfaceExtFound = 1;
892 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
893 }
894#endif
895 assert(enabled_extension_count < 64);
896 }
897 }
898
899 if(!surfaceExtFound)
900 {
901 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME " extension.\n\n"
902 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
903 "Please look at the Getting Started guide for additional information.\n",
904 "vkCreateInstance Failure");
905 }
906
907 if(!platformSurfaceExtFound)
908 {
909#if defined(VK_USE_PLATFORM_WIN32_KHR)
910 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME " extension.\n\n"
911 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
912 "Please look at the Getting Started guide for additional information.\n",
913 "vkCreateInstance Failure");
914#elif defined(VK_USE_PLATFORM_XCB_KHR)
915 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME " extension.\n\n"
916 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
917 "Please look at the Getting Started guide for additional information.\n",
918 "vkCreateInstance Failure");
919#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
920 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME " extension.\n\n"
921 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
922 "Please look at the Getting Started guide for additional information.\n",
923 "vkCreateInstance Failure");
924#endif
925 }
926
927#if defined(VK_USE_PLATFORM_XLIB_KHR)
928 if(use_xlib && !xlibSurfaceExtFound)
929 {
930 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME " extension.\n\n"
931 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
932 "Please look at the Getting Started guide for additional information.\n",
933 "vkCreateInstance Failure");
934 }
935#endif
936
937 auto const app = vk::ApplicationInfo()
938 .setPApplicationName(APP_SHORT_NAME)
939 .setApplicationVersion(0)
940 .setPEngineName(APP_SHORT_NAME)
941 .setEngineVersion(0)
942 .setApiVersion(VK_API_VERSION_1_0);
943 auto const inst_info = vk::InstanceCreateInfo()
944 .setPApplicationInfo(&app)
945 .setEnabledLayerCount(enabled_layer_count)
946 .setPpEnabledLayerNames(instance_validation_layers)
947 .setEnabledExtensionCount(enabled_extension_count)
948 .setPpEnabledExtensionNames(extension_names);
949
950 result = vk::createInstance(&inst_info, nullptr, &inst);
951 if(result == vk::Result::eErrorIncompatibleDriver)
952 {
953 ERR_EXIT("Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
954 "Please look at the Getting Started guide for additional information.\n",
955 "vkCreateInstance Failure");
956 }
957 else if(result == vk::Result::eErrorExtensionNotPresent)
958 {
959 ERR_EXIT("Cannot find a specified extension library.\n"
960 "Make sure your layers path is set appropriately.\n",
961 "vkCreateInstance Failure");
962 }
963 else if(result != vk::Result::eSuccess)
964 {
965 ERR_EXIT("vkCreateInstance failed.\n\n"
966 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
967 "Please look at the Getting Started guide for additional information.\n",
968 "vkCreateInstance Failure");
969 }
970
971 /* Make initial call to query gpu_count, then second call for gpu info*/
972 uint32_t gpu_count;
973 result = inst.enumeratePhysicalDevices(&gpu_count, nullptr);
974 VERIFY(result == vk::Result::eSuccess);
975 assert(gpu_count > 0);
976
977 if(gpu_count > 0)
978 {
979 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
980 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
981 VERIFY(result == vk::Result::eSuccess);
982 /* For cube demo we just grab the first physical device */
983 gpu = physical_devices[0];
984 }
985 else
986 {
987 ERR_EXIT("vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
988 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
989 "Please look at the Getting Started guide for additional information.\n",
990 "vkEnumeratePhysicalDevices Failure");
991 }
992
993 /* Look for device extensions */
994 uint32_t device_extension_count = 0;
995 vk::Bool32 swapchainExtFound = VK_FALSE;
996 enabled_extension_count = 0;
997 memset(extension_names, 0, sizeof(extension_names));
998
999 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, nullptr);
1000 VERIFY(result == vk::Result::eSuccess);
1001
1002 if(device_extension_count > 0)
1003 {
1004 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1005 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
1006 VERIFY(result == vk::Result::eSuccess);
1007
1008 for(uint32_t i = 0; i < device_extension_count; i++)
1009 {
1010 if(!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName))
1011 {
1012 swapchainExtFound = 1;
1013 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
1014 }
1015 assert(enabled_extension_count < 64);
1016 }
1017 }
1018
1019 if(!swapchainExtFound)
1020 {
1021 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME " extension.\n\n"
1022 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1023 "Please look at the Getting Started guide for additional information.\n",
1024 "vkCreateInstance Failure");
1025 }
1026
1027 gpu.getProperties(&gpu_props);
1028
1029 /* Call with nullptr data to get count */
1030 gpu.getQueueFamilyProperties(&queue_family_count, nullptr);
1031 assert(queue_family_count >= 1);
1032
1033 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1034 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
1035
1036 // Query fine-grained feature support for this device.
1037 // If app has specific feature requirements it should check supported
1038 // features based on this query
1039 vk::PhysicalDeviceFeatures physDevFeatures;
1040 gpu.getFeatures(&physDevFeatures);
1041 }
1042
1043 void init_vk_swapchain()
1044 {
1045 // Create a WSI surface for the window:
1046#if defined(VK_USE_PLATFORM_WIN32_KHR)
1047 {
1048 auto const createInfo = vk::Win32SurfaceCreateInfoKHR()
1049 .setHinstance(connection)
1050 .setHwnd(window);
1051
1052 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1053 VERIFY(result == vk::Result::eSuccess);
1054 }
1055#elif defined(VK_USE_PLATFORM_WAYLAND_KHR) && !defined(VK_USE_PLATFORM_XCB_KHR)
1056 {
1057 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR()
1058 .setDisplay(display)
1059 .setSurface(window);
1060
1061 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1062 VERIFY(result == vk::Result::eSuccess);
1063 }
1064#endif
1065 if(use_xlib)
1066 {
1067#if defined(VK_USE_PLATFORM_XLIB_KHR)
1068 auto const createInfo = vk::XlibSurfaceCreateInfoKHR()
1069 .setDpy(display)
1070 .setWindow(xlib_window);
1071
1072 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1073 VERIFY(result == vk::Result::eSuccess);
1074#endif
1075 }
1076 else
1077 {
1078#if defined(VK_USE_PLATFORM_XCB_KHR)
1079 auto const createInfo = vk::XcbSurfaceCreateInfoKHR()
1080 .setConnection(connection)
1081 .setWindow(xcb_window);
1082
1083 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1084 VERIFY(result == vk::Result::eSuccess);
1085#endif
1086 }
1087
1088 // Iterate over each queue to learn whether it supports presenting:
1089 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1090 for(uint32_t i = 0; i < queue_family_count; i++)
1091 {
1092 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1093 }
1094
1095 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1096 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1097 for(uint32_t i = 0; i < queue_family_count; i++)
1098 {
1099 if(queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics)
1100 {
1101 if(graphicsQueueFamilyIndex == UINT32_MAX)
1102 {
1103 graphicsQueueFamilyIndex = i;
1104 }
1105
1106 if (supportsPresent[i] == VK_TRUE)
1107 {
1108 graphicsQueueFamilyIndex = i;
1109 presentQueueFamilyIndex = i;
1110 break;
1111 }
1112 }
1113 }
1114
1115 if(presentQueueFamilyIndex == UINT32_MAX)
1116 {
1117 // If didn't find a queue that supports both graphics and present, then
1118 // find a separate present queue.
1119 for(uint32_t i = 0; i < queue_family_count; ++i)
1120 {
1121 if(supportsPresent[i] == VK_TRUE)
1122 {
1123 presentQueueFamilyIndex = i;
1124 break;
1125 }
1126 }
1127 }
1128
1129 // Generate error if could not find both a graphics and a present queue
1130 if(graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX)
1131 {
1132 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1133 }
1134
1135 graphics_queue_family_index = graphicsQueueFamilyIndex;
1136 present_queue_family_index = presentQueueFamilyIndex;
1137 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1138
1139 create_device();
1140
1141 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1142 if(!separate_present_queue)
1143 {
1144 present_queue = graphics_queue;
1145 }
1146 else
1147 {
1148 device.getQueue(present_queue_family_index, 0, &present_queue);
1149 }
1150
1151 // Get the list of VkFormat's that are supported:
1152 uint32_t formatCount;
1153 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, nullptr);
1154 VERIFY(result == vk::Result::eSuccess);
1155
1156 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1157 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1158 VERIFY(result == vk::Result::eSuccess);
1159
1160 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1161 // the surface has no preferred format. Otherwise, at least one
1162 // supported format will be returned.
1163 if(formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined)
1164 {
1165 format = vk::Format::eB8G8R8A8Unorm;
1166 }
1167 else
1168 {
1169 assert(formatCount >= 1);
1170 format = surfFormats[0].format;
1171 }
1172 color_space = surfFormats[0].colorSpace;
1173
1174 quit = false;
1175 curFrame = 0;
1176
1177 // Create semaphores to synchronize acquiring presentable buffers before
1178 // rendering and waiting for drawing to be complete before presenting
1179 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1180
1181 // Create fences that we can use to throttle if we get too far
1182 // ahead of the image presents
1183 vk::FenceCreateInfo const fence_ci;
1184 for(uint32_t i = 0; i < FRAME_LAG; i++)
1185 {
1186 device.createFence(&fence_ci, nullptr, &fences[i]);
1187 fencesInited[i] = false;
1188 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1189 VERIFY(result == vk::Result::eSuccess);
1190
1191 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1192 VERIFY(result == vk::Result::eSuccess);
1193
1194 if(separate_present_queue)
1195 {
1196 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1197 VERIFY(result == vk::Result::eSuccess);
1198 }
1199 }
1200 frame_index = 0;
1201
1202 // Get Memory information and properties
1203 gpu.getMemoryProperties(&memory_properties);
1204 }
1205
1206 void prepare()
1207 {
1208 auto const cmd_pool_info = vk::CommandPoolCreateInfo()
1209 .setQueueFamilyIndex(graphics_queue_family_index);
1210 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1211 VERIFY(result == vk::Result::eSuccess);
1212
1213 auto const cmd = vk::CommandBufferAllocateInfo()
1214 .setCommandPool(cmd_pool)
1215 .setLevel(vk::CommandBufferLevel::ePrimary)
1216 .setCommandBufferCount(1);
1217
1218 prepare_buffers();
1219 prepare_depth();
1220 prepare_textures();
1221 prepare_cube_data_buffer();
1222
1223 prepare_descriptor_layout();
1224 prepare_render_pass();
1225 prepare_pipeline();
1226
1227 for(uint32_t i = 0; i < swapchainImageCount; ++i)
1228 {
1229 result = device.allocateCommandBuffers(&cmd, &buffers[i].cmd);
1230 VERIFY(result == vk::Result::eSuccess);
1231 }
1232
1233 if(separate_present_queue)
1234 {
1235 auto const cmd_pool_info = vk::CommandPoolCreateInfo()
1236 .setQueueFamilyIndex(present_queue_family_index);
1237
1238 result = device.createCommandPool(&cmd_pool_info, nullptr, &present_cmd_pool);
1239 VERIFY(result == vk::Result::eSuccess);
1240
1241 auto const cmd = vk::CommandBufferAllocateInfo()
1242 .setCommandPool(present_cmd_pool)
1243 .setLevel(vk::CommandBufferLevel::ePrimary)
1244 .setCommandBufferCount(1);
1245
1246 for(uint32_t i = 0; i < swapchainImageCount; i++)
1247 {
1248 result = device.allocateCommandBuffers(&cmd, &buffers[i].graphics_to_present_cmd);
1249 VERIFY(result == vk::Result::eSuccess);
1250
1251 build_image_ownership_cmd(i);
1252 }
1253 }
1254
1255 prepare_descriptor_pool();
1256 prepare_descriptor_set();
1257
1258 prepare_framebuffers();
1259
1260 for(uint32_t i = 0; i < swapchainImageCount; ++i)
1261 {
1262 current_buffer = i;
1263 draw_build_cmd(buffers[i].cmd);
1264 }
1265
1266 /*
1267 * Prepare functions above may generate pipeline commands
1268 * that need to be flushed before beginning the render loop.
1269 */
1270 flush_init_cmd();
1271
1272 current_buffer = 0;
1273 prepared = true;
1274 }
1275
1276 void prepare_buffers()
1277 {
1278 vk::SwapchainKHR oldSwapchain = swapchain;
1279
1280 // Check the surface capabilities and formats
1281 vk::SurfaceCapabilitiesKHR surfCapabilities;
1282 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1283 VERIFY(result == vk::Result::eSuccess);
1284
1285 uint32_t presentModeCount;
1286 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, nullptr);
1287 VERIFY(result == vk::Result::eSuccess);
1288
1289 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1290 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1291 VERIFY(result == vk::Result::eSuccess);
1292
1293 vk::Extent2D swapchainExtent;
1294 // width and height are either both -1, or both not -1.
1295 if(surfCapabilities.currentExtent.width == (uint32_t)-1)
1296 {
1297 // If the surface size is undefined, the size is set to
1298 // the size of the images requested.
1299 swapchainExtent.width = width;
1300 swapchainExtent.height = height;
1301 }
1302 else
1303 {
1304 // If the surface size is defined, the swap chain size must match
1305 swapchainExtent = surfCapabilities.currentExtent;
1306 width = surfCapabilities.currentExtent.width;
1307 height = surfCapabilities.currentExtent.height;
1308 }
1309
1310 // The FIFO present mode is guaranteed by the spec to be supported
1311 // and to have no tearing. It's a great default present mode to use.
1312 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1313
1314 // There are times when you may wish to use another present mode. The
1315 // following code shows how to select them, and the comments provide some
1316 // reasons you may wish to use them.
1317 //
1318 // It should be noted that Vulkan 1.0 doesn't provide a method for
1319 // synchronizing rendering with the presentation engine's display. There
1320 // is a method provided for throttling rendering with the display, but
1321 // there are some presentation engines for which this method will not work.
1322 // If an application doesn't throttle its rendering, and if it renders much
1323 // faster than the refresh rate of the display, this can waste power on
1324 // mobile devices. That is because power is being spent rendering images
1325 // that may never be seen.
1326//#define DESIRE_VK_PRESENT_MODE_IMMEDIATE_KHR
1327//#define DESIRE_VK_PRESENT_MODE_MAILBOX_KHR
1328//#define DESIRE_VK_PRESENT_MODE_FIFO_RELAXED_KHR
1329#if defined(DESIRE_VK_PRESENT_MODE_IMMEDIATE_KHR)
1330 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
1331 // tearing, or have some way of synchronizing their rendering with the
1332 // display.
1333 for(size_t i = 0; i < presentModeCount; ++i)
1334 {
1335 if(presentModes[i] == vk::PresentModeKHR::eImmediate)
1336 {
1337 swapchainPresentMode = vk::PresentModeKHR::eImmediate;
1338 break;
1339 }
1340 }
1341#elif defined(DESIRE_VK_PRESENT_MODE_MAILBOX_KHR)
1342 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1343 // generally render a new presentable image every refresh cycle, but are
1344 // occasionally early. In this case, the application wants the new image
1345 // to be displayed instead of the previously-queued-for-presentation image
1346 // that has not yet been displayed.
1347 for(size_t i = 0; i < presentModeCount; ++i)
1348 {
1349 if (presentModes[i] == vk::PresentModeKHR::eMailbox)
1350 {
1351 swapchainPresentMode = vk::PresentModeKHR::eMailbox;
1352 break;
1353 }
1354 }
1355#elif defined(DESIRE_VK_PRESENT_MODE_FIFO_RELAXED_KHR)
1356 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1357 // render a new presentable image every refresh cycle, but are occasionally
1358 // late. In this case (perhaps because of stuttering/latency concerns),
1359 // the application wants the late image to be immediately displayed, even
1360 // though that may mean some tearing.
1361 for(size_t i = 0; i < presentModeCount; ++i)
1362 {
1363 if(presentModes[i] == vk::PresentModeKHR::eFifoRelaxed)
1364 {
1365 swapchainPresentMode = vk::PresentModeKHR::eFifoRelaxed;
1366 break;
1367 }
1368 }
1369#endif
1370
1371 // Determine the number of VkImage's to use in the swap chain (we desire to
1372 // own only 1 image at a time, besides the images being displayed and
1373 // queued for display):
1374 uint32_t desiredNumberOfSwapchainImages = surfCapabilities.minImageCount + 1;
1375 // If maxImageCount is 0, we can ask for as many images as we want, otherwise
1376 // we're limited to maxImageCount
1377 if((surfCapabilities.maxImageCount > 0) && (desiredNumberOfSwapchainImages > surfCapabilities.maxImageCount))
1378 {
1379 // Application must settle for fewer images than desired:
1380 desiredNumberOfSwapchainImages = surfCapabilities.maxImageCount;
1381 }
1382
1383 vk::SurfaceTransformFlagBitsKHR preTransform;
1384 if(surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity)
1385 {
1386 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1387 }
1388 else
1389 {
1390 preTransform = surfCapabilities.currentTransform;
1391 }
1392
1393 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1394 .setSurface(surface)
1395 .setMinImageCount(desiredNumberOfSwapchainImages)
1396 .setImageFormat(format)
1397 .setImageColorSpace(color_space)
1398 .setImageExtent({ swapchainExtent.width, swapchainExtent.height })
1399 .setImageArrayLayers(1)
1400 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1401 .setImageSharingMode(vk::SharingMode::eExclusive)
1402 .setQueueFamilyIndexCount(0)
1403 .setPQueueFamilyIndices(nullptr)
1404 .setPreTransform(preTransform)
1405 .setCompositeAlpha(vk::CompositeAlphaFlagBitsKHR::eOpaque)
1406 .setPresentMode(swapchainPresentMode)
1407 .setClipped(true)
1408 .setOldSwapchain(oldSwapchain);
1409
1410 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1411 VERIFY(result == vk::Result::eSuccess);
1412
1413 // If we just re-created an existing swapchain, we should destroy the old
1414 // swapchain at this point.
1415 // Note: destroying the swapchain also cleans up all its associated
1416 // presentable images once the platform is done with them.
1417 if(oldSwapchain)
1418 {
1419 device.destroySwapchainKHR(oldSwapchain, nullptr);
1420 }
1421
1422 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, nullptr);
1423 VERIFY(result == vk::Result::eSuccess);
1424
1425 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1426 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1427 VERIFY(result == vk::Result::eSuccess);
1428
1429 buffers.reset(new SwapchainBuffers[swapchainImageCount]);
1430
1431 for(uint32_t i = 0; i < swapchainImageCount; ++i)
1432 {
1433 auto const color_image_view = vk::ImageViewCreateInfo()
1434 .setImage(swapchainImages[i])
1435 .setViewType(vk::ImageViewType::e2D)
1436 .setFormat(format)
1437 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1438
1439 buffers[i].image = swapchainImages[i];
1440
1441 result = device.createImageView(&color_image_view, nullptr, &buffers[i].view);
1442 VERIFY(result == vk::Result::eSuccess);
1443
1444 // The draw loop will be expecting the presentable images to be in
1445 // LAYOUT_PRESENT_SRC_KHR since that's how they're left at the end of every frame.
1446 set_image_layout(buffers[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eUndefined,
1447 vk::ImageLayout::ePresentSrcKHR, vk::AccessFlagBits());
1448 }
1449 }
1450
1451 void prepare_cube_data_buffer()
1452 {
1453 mat4x4 VP;
1454 mat4x4_mul(VP, projection_matrix, view_matrix);
1455
1456 mat4x4 MVP;
1457 mat4x4_mul(MVP, VP, model_matrix);
1458
1459 vktexcube_vs_uniform data;
1460 memcpy(data.mvp, MVP, sizeof(MVP));
1461 // dumpMatrix("MVP", MVP)
1462 for(int32_t i = 0; i < 12 * 3; i++)
1463 {
1464 data.position[i][0] = g_vertex_buffer_data[i * 3];
1465 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1466 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1467 data.position[i][3] = 1.0f;
1468 data.attr[i][0] = g_uv_buffer_data[2 * i];
1469 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1470 data.attr[i][2] = 0;
1471 data.attr[i][3] = 0;
1472 }
1473
1474 auto const buf_info = vk::BufferCreateInfo()
1475 .setSize(sizeof(data))
1476 .setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1477 auto result = device.createBuffer(&buf_info, nullptr, &uniform_data.buf);
1478 VERIFY(result == vk::Result::eSuccess);
1479
1480 vk::MemoryRequirements mem_reqs;
1481 device.getBufferMemoryRequirements(uniform_data.buf, &mem_reqs);
1482
1483 uniform_data.mem_alloc.setAllocationSize(mem_reqs.size);
1484 uniform_data.mem_alloc.setMemoryTypeIndex(0);
1485
1486 bool const pass = memory_type_from_properties(mem_reqs.memoryTypeBits,
1487 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1488 &uniform_data.mem_alloc.memoryTypeIndex);
1489 VERIFY(pass);
1490
1491 result = device.allocateMemory(&uniform_data.mem_alloc, nullptr, &(uniform_data.mem));
1492 VERIFY(result == vk::Result::eSuccess);
1493
1494 auto pData = device.mapMemory(uniform_data.mem, 0, uniform_data.mem_alloc.allocationSize, vk::MemoryMapFlags());
1495 VERIFY(pData.result == vk::Result::eSuccess);
1496
1497 memcpy(pData.value, &data, sizeof data);
1498
1499 device.unmapMemory(uniform_data.mem);
1500
1501 result = device.bindBufferMemory(uniform_data.buf, uniform_data.mem, 0);
1502 VERIFY(result == vk::Result::eSuccess);
1503
1504 uniform_data.buffer_info.buffer = uniform_data.buf;
1505 uniform_data.buffer_info.offset = 0;
1506 uniform_data.buffer_info.range = sizeof(data);
1507 }
1508
1509 void prepare_depth()
1510 {
1511 depth.format = vk::Format::eD16Unorm;
1512
1513 auto const image = vk::ImageCreateInfo()
1514 .setImageType(vk::ImageType::e2D)
1515 .setFormat(depth.format)
1516 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1517 .setMipLevels(1)
1518 .setArrayLayers(1)
1519 .setSamples(vk::SampleCountFlagBits::e1)
1520 .setTiling(vk::ImageTiling::eOptimal)
1521 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1522 .setSharingMode(vk::SharingMode::eExclusive)
1523 .setQueueFamilyIndexCount(0)
1524 .setPQueueFamilyIndices(nullptr)
1525 .setInitialLayout(vk::ImageLayout::eUndefined);
1526
1527 auto result = device.createImage(&image, nullptr, &depth.image);
1528 VERIFY(result == vk::Result::eSuccess);
1529
1530 vk::MemoryRequirements mem_reqs;
1531 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1532
1533 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1534 depth.mem_alloc.setMemoryTypeIndex(0);
1535
1536 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits(0),
1537 &depth.mem_alloc.memoryTypeIndex);
1538 VERIFY(pass);
1539
1540 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1541 VERIFY(result == vk::Result::eSuccess);
1542
1543 result = device.bindImageMemory(depth.image, depth.mem, 0);
1544 VERIFY(result == vk::Result::eSuccess);
1545
1546 set_image_layout(depth.image, vk::ImageAspectFlagBits::eDepth, vk::ImageLayout::eUndefined,
1547 vk::ImageLayout::eDepthStencilAttachmentOptimal, vk::AccessFlagBits());
1548
1549 auto const view = vk::ImageViewCreateInfo()
1550 .setImage(depth.image)
1551 .setViewType(vk::ImageViewType::e2D)
1552 .setFormat(depth.format)
1553 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1554 result = device.createImageView(&view, nullptr, &depth.view);
1555 VERIFY(result == vk::Result::eSuccess);
1556 }
1557
1558 void prepare_descriptor_layout()
1559 {
1560 vk::DescriptorSetLayoutBinding const layout_bindings[2] =
1561 {
1562 vk::DescriptorSetLayoutBinding()
1563 .setBinding(0)
1564 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1565 .setDescriptorCount(1)
1566 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1567 .setPImmutableSamplers(nullptr),
1568 vk::DescriptorSetLayoutBinding()
1569 .setBinding(1)
1570 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1571 .setDescriptorCount(texture_count)
1572 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1573 .setPImmutableSamplers(nullptr)
1574 };
1575
1576 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo()
1577 .setBindingCount(2)
1578 .setPBindings(layout_bindings);
1579
1580 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1581 VERIFY(result == vk::Result::eSuccess);
1582
1583 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo()
1584 .setSetLayoutCount(1)
1585 .setPSetLayouts(&desc_layout);
1586
1587 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1588 VERIFY(result == vk::Result::eSuccess);
1589 }
1590
1591 void prepare_descriptor_pool()
1592 {
1593 vk::DescriptorPoolSize const poolSizes[2] =
1594 {
1595 vk::DescriptorPoolSize()
1596 .setType(vk::DescriptorType::eUniformBuffer)
1597 .setDescriptorCount(1),
1598 vk::DescriptorPoolSize()
1599 .setType(vk::DescriptorType::eCombinedImageSampler)
1600 .setDescriptorCount(texture_count)
1601 };
1602
1603 auto const descriptor_pool = vk::DescriptorPoolCreateInfo()
1604 .setMaxSets(1)
1605 .setPoolSizeCount(2)
1606 .setPPoolSizes(poolSizes);
1607
1608 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1609 VERIFY(result == vk::Result::eSuccess);
1610 }
1611
1612 void prepare_descriptor_set()
1613 {
1614 auto const alloc_info = vk::DescriptorSetAllocateInfo()
1615 .setDescriptorPool(desc_pool)
1616 .setDescriptorSetCount(1)
1617 .setPSetLayouts(&desc_layout);
1618 auto result = device.allocateDescriptorSets(&alloc_info, &desc_set);
1619 VERIFY(result == vk::Result::eSuccess);
1620
1621 vk::DescriptorImageInfo tex_descs[texture_count];
1622 for(uint32_t i = 0; i < texture_count; i++)
1623 {
1624 tex_descs[i].setSampler(textures[i].sampler);
1625 tex_descs[i].setImageView(textures[i].view);
1626 tex_descs[i].setImageLayout(vk::ImageLayout::eGeneral);
1627 }
1628
1629 vk::WriteDescriptorSet writes[2];
1630
1631 writes[0].setDstSet(desc_set);
1632 writes[0].setDescriptorCount(1);
1633 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1634 writes[0].setPBufferInfo(&uniform_data.buffer_info);
1635
1636 writes[1].setDstSet(desc_set);
1637 writes[1].setDstBinding(1);
1638 writes[1].setDescriptorCount(texture_count);
1639 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1640 writes[1].setPImageInfo(tex_descs);
1641
1642 device.updateDescriptorSets(2, writes, 0, nullptr);
1643 }
1644
1645 void prepare_framebuffers()
1646 {
1647 vk::ImageView attachments[2];
1648 attachments[1] = depth.view;
1649
1650 auto const fb_info = vk::FramebufferCreateInfo()
1651 .setRenderPass(render_pass)
1652 .setAttachmentCount(2)
1653 .setPAttachments(attachments)
1654 .setWidth((uint32_t)width)
1655 .setHeight((uint32_t)height)
1656 .setLayers(1);
1657
1658 framebuffers.reset(new vk::Framebuffer[swapchainImageCount]);
1659
1660 for(uint32_t i = 0; i < swapchainImageCount; i++)
1661 {
1662 attachments[0] = buffers[i].view;
1663 auto const result = device.createFramebuffer(&fb_info, nullptr, &framebuffers[i]);
1664 VERIFY(result == vk::Result::eSuccess);
1665 }
1666 }
1667
1668 vk::ShaderModule prepare_fs()
1669 {
1670 size_t size;
1671 void *fragShaderCode = read_spv("cube-frag.spv", &size);
1672
1673 frag_shader_module = prepare_shader_module(fragShaderCode, size);
1674
1675 free(fragShaderCode);
1676
1677 return frag_shader_module;
1678 }
1679
1680 void prepare_pipeline()
1681 {
1682 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1683 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1684 VERIFY(result == vk::Result::eSuccess);
1685
1686 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] =
1687 {
1688 vk::PipelineShaderStageCreateInfo()
1689 .setStage(vk::ShaderStageFlagBits::eVertex)
1690 .setModule(prepare_vs())
1691 .setPName("main"),
1692 vk::PipelineShaderStageCreateInfo()
1693 .setStage(vk::ShaderStageFlagBits::eFragment)
1694 .setModule(prepare_fs())
1695 .setPName("main")
1696 };
1697
1698 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1699
1700 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo()
1701 .setTopology(vk::PrimitiveTopology::eTriangleList);
1702
1703 // TODO: Where are pViewports and pScissors set?
1704 auto const viewportInfo = vk::PipelineViewportStateCreateInfo()
1705 .setViewportCount(1)
1706 .setScissorCount(1);
1707
1708 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1709 .setDepthClampEnable(VK_FALSE)
1710 .setRasterizerDiscardEnable(VK_FALSE)
1711 .setPolygonMode(vk::PolygonMode::eFill)
1712 .setCullMode(vk::CullModeFlagBits::eBack)
1713 .setFrontFace(vk::FrontFace::eCounterClockwise)
1714 .setDepthBiasEnable(VK_FALSE)
1715 .setLineWidth(1.0f);
1716
1717 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1718
1719 auto const stencilOp = vk::StencilOpState()
1720 .setFailOp(vk::StencilOp::eKeep)
1721 .setPassOp(vk::StencilOp::eKeep)
1722 .setCompareOp(vk::CompareOp::eAlways);
1723
1724 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1725 .setDepthTestEnable(VK_TRUE)
1726 .setDepthWriteEnable(VK_TRUE)
1727 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1728 .setDepthBoundsTestEnable(VK_FALSE)
1729 .setStencilTestEnable(VK_FALSE)
1730 .setFront(stencilOp)
1731 .setBack(stencilOp);
1732
1733 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] =
1734 {
1735 vk::PipelineColorBlendAttachmentState()
1736 .setColorWriteMask(vk::ColorComponentFlagBits::eR| vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB
1737 | vk::ColorComponentFlagBits::eA)
1738 };
1739
1740 auto const colorBlendInfo = vk::PipelineColorBlendStateCreateInfo()
1741 .setAttachmentCount(1)
1742 .setPAttachments(colorBlendAttachments);
1743
1744 vk::DynamicState const dynamicStates[2] =
1745 {
1746 vk::DynamicState::eViewport,
1747 vk::DynamicState::eScissor
1748 };
1749
1750 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo()
1751 .setPDynamicStates(dynamicStates)
1752 .setDynamicStateCount(2);
1753
1754 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1755 .setStageCount(2)
1756 .setPStages(shaderStageInfo)
1757 .setPVertexInputState(&vertexInputInfo)
1758 .setPInputAssemblyState(&inputAssemblyInfo)
1759 .setPViewportState(&viewportInfo)
1760 .setPRasterizationState(&rasterizationInfo)
1761 .setPMultisampleState(&multisampleInfo)
1762 .setPDepthStencilState(&depthStencilInfo)
1763 .setPColorBlendState(&colorBlendInfo)
1764 .setPDynamicState(&dynamicStateInfo)
1765 .setLayout(pipeline_layout)
1766 .setRenderPass(render_pass);
1767
1768 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1769 VERIFY(result == vk::Result::eSuccess);
1770
1771 device.destroyShaderModule(frag_shader_module, nullptr);
1772 device.destroyShaderModule(vert_shader_module, nullptr);
1773 }
1774
1775 void prepare_render_pass()
1776 {
1777 const vk::AttachmentDescription attachments[2] =
1778 {
1779 vk::AttachmentDescription()
1780 .setFlags(vk::AttachmentDescriptionFlagBits::eMayAlias)
1781 .setFormat(format)
1782 .setSamples(vk::SampleCountFlagBits::e1)
1783 .setLoadOp(vk::AttachmentLoadOp::eClear)
1784 .setStoreOp(vk::AttachmentStoreOp::eStore)
1785 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1786 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1787 .setInitialLayout(vk::ImageLayout::eColorAttachmentOptimal)
1788 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1789 vk::AttachmentDescription()
1790 .setFlags(vk::AttachmentDescriptionFlagBits::eMayAlias)
1791 .setFormat(depth.format)
1792 .setSamples(vk::SampleCountFlagBits::e1)
1793 .setLoadOp(vk::AttachmentLoadOp::eClear)
1794 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1795 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1796 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1797 .setInitialLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)
1798 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)
1799 };
1800
1801 auto const color_reference = vk::AttachmentReference()
1802 .setAttachment(0)
1803 .setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1804
1805 auto const depth_reference = vk::AttachmentReference()
1806 .setAttachment(1)
1807 .setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1808
1809 auto const subpass = vk::SubpassDescription()
1810 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1811 .setInputAttachmentCount(0)
1812 .setPInputAttachments(nullptr)
1813 .setColorAttachmentCount(1)
1814 .setPColorAttachments(&color_reference)
1815 .setPResolveAttachments(nullptr)
1816 .setPDepthStencilAttachment(&depth_reference)
1817 .setPreserveAttachmentCount(0)
1818 .setPPreserveAttachments(nullptr);
1819
1820 auto const rp_info = vk::RenderPassCreateInfo()
1821 .setAttachmentCount(2)
1822 .setPAttachments(attachments)
1823 .setSubpassCount(1)
1824 .setPSubpasses(&subpass)
1825 .setDependencyCount(0)
1826 .setPDependencies(nullptr);
1827
1828 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
1829 VERIFY(result == vk::Result::eSuccess);
1830 }
1831
1832 vk::ShaderModule prepare_shader_module(const void *code, size_t size)
1833 {
1834 auto const moduleCreateInfo = vk::ShaderModuleCreateInfo()
1835 .setCodeSize(size)
1836 .setPCode((uint32_t const*)code);
1837
1838 vk::ShaderModule module;
1839 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
1840 VERIFY(result == vk::Result::eSuccess);
1841
1842 return module;
1843 }
1844
1845 void prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling,
1846 vk::ImageUsageFlags usage, vk::MemoryPropertyFlags required_props)
1847 {
1848 int32_t tex_width;
1849 int32_t tex_height;
1850 if(!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height))
1851 {
1852 ERR_EXIT("Failed to load textures", "Load Texture Failure");
1853 }
1854
1855 tex_obj->tex_width = tex_width;
1856 tex_obj->tex_height = tex_height;
1857
1858 auto const image_create_info = vk::ImageCreateInfo()
1859 .setImageType(vk::ImageType::e2D)
1860 .setFormat(vk::Format::eR8G8B8A8Unorm)
1861 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
1862 .setMipLevels(1)
1863 .setArrayLayers(1)
1864 .setSamples(vk::SampleCountFlagBits::e1)
1865 .setTiling(tiling)
1866 .setUsage(usage)
1867 .setSharingMode(vk::SharingMode::eExclusive)
1868 .setQueueFamilyIndexCount(0)
1869 .setPQueueFamilyIndices(nullptr)
1870 .setInitialLayout(vk::ImageLayout::ePreinitialized);
1871
1872 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
1873 VERIFY(result == vk::Result::eSuccess);
1874
1875 vk::MemoryRequirements mem_reqs;
1876 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
1877
1878 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
1879 tex_obj->mem_alloc.setMemoryTypeIndex(0);
1880
1881 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
1882 VERIFY(pass == true);
1883
1884 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
1885 VERIFY(result == vk::Result::eSuccess);
1886
1887 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
1888 VERIFY(result == vk::Result::eSuccess);
1889
1890 if(required_props & vk::MemoryPropertyFlagBits::eHostVisible)
1891 {
1892 auto const subres = vk::ImageSubresource()
1893 .setAspectMask(vk::ImageAspectFlagBits::eColor)
1894 .setMipLevel(0)
1895 .setArrayLayer(0);
1896 vk::SubresourceLayout layout;
1897 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
1898
1899 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
1900 VERIFY(data.result == vk::Result::eSuccess);
1901
1902 if(!loadTexture(filename, (uint8_t*)data.value, &layout, &tex_width, &tex_height))
1903 {
1904 fprintf(stderr, "Error loading texture: %s\n", filename);
1905 }
1906
1907 device.unmapMemory(tex_obj->mem);
1908 }
1909
1910 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1911 set_image_layout(tex_obj->image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized, tex_obj->imageLayout,
1912 vk::AccessFlagBits::eHostWrite);
1913 }
1914
1915 void prepare_textures()
1916 {
1917 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
1918 vk::FormatProperties props;
1919 gpu.getFormatProperties(tex_format, &props);
1920
1921 for(uint32_t i = 0; i < texture_count; i++)
1922 {
1923 if((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer)
1924 {
1925 /* Device can texture using linear textures */
1926 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear,
1927 vk::ImageUsageFlagBits::eSampled,
1928 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
1929 }
1930 else if(props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage)
1931 {
1932 /* Must use staging buffer to copy linear texture to optimized */
1933 texture_object staging_texture;
1934
1935 prepare_texture_image(tex_files[i], &staging_texture, vk::ImageTiling::eLinear,
1936 vk::ImageUsageFlagBits::eTransferSrc,
1937 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
1938
1939 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
1940 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
1941 vk::MemoryPropertyFlagBits::eDeviceLocal);
1942
1943 set_image_layout(staging_texture.image, vk::ImageAspectFlagBits::eColor, staging_texture.imageLayout,
1944 vk::ImageLayout::eTransferSrcOptimal, vk::AccessFlags());
1945
1946 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, textures[i].imageLayout,
1947 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlags());
1948
1949 auto const subresource = vk::ImageSubresourceLayers()
1950 .setAspectMask(vk::ImageAspectFlagBits::eColor)
1951 .setMipLevel(0)
1952 .setBaseArrayLayer(0)
1953 .setLayerCount(1);
1954
1955 auto const copy_region = vk::ImageCopy()
1956 .setSrcSubresource(subresource)
1957 .setSrcOffset({0, 0, 0})
1958 .setDstSubresource(subresource)
1959 .setDstOffset({0, 0, 0})
1960 .setExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
1961
1962 cmd.copyImage(staging_texture.image, vk::ImageLayout::eTransferSrcOptimal, textures[i].image,
1963 vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
1964
1965 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
1966 textures[i].imageLayout, vk::AccessFlags());
1967
1968 flush_init_cmd();
1969
1970 destroy_texture_image(&staging_texture);
1971 }
1972 else
1973 {
1974 assert(!"No support for R8G8B8A8_UNORM as texture image format");
1975 }
1976
1977 auto const samplerInfo = vk::SamplerCreateInfo()
1978 .setMagFilter(vk::Filter::eNearest)
1979 .setMinFilter(vk::Filter::eNearest)
1980 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
1981 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
1982 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
1983 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
1984 .setMipLodBias(0.0f)
1985 .setAnisotropyEnable(VK_FALSE)
1986 .setMaxAnisotropy(1)
1987 .setCompareEnable(VK_FALSE)
1988 .setCompareOp(vk::CompareOp::eNever)
1989 .setMinLod(0.0f)
1990 .setMaxLod(0.0f)
1991 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
1992 .setUnnormalizedCoordinates(VK_FALSE);
1993
1994 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
1995 VERIFY(result == vk::Result::eSuccess);
1996
1997 auto const viewInfo = vk::ImageViewCreateInfo()
1998 .setImage(textures[i].image)
1999 .setViewType(vk::ImageViewType::e2D)
2000 .setFormat(tex_format)
2001 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2002
2003 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2004 VERIFY(result == vk::Result::eSuccess);
2005 }
2006 }
2007
2008 vk::ShaderModule prepare_vs()
2009 {
2010 size_t size;
2011 void* vertShaderCode = read_spv("cube-vert.spv", &size);
2012
2013 vert_shader_module = prepare_shader_module(vertShaderCode, size);
2014
2015 free(vertShaderCode);
2016
2017 return vert_shader_module;
2018 }
2019
2020 char *read_spv(const char *filename, size_t *psize)
2021 {
2022 FILE *fp = fopen(filename, "rb");
2023 if(!fp)
2024 {
2025 return nullptr;
2026 }
2027
2028 fseek(fp, 0L, SEEK_END);
2029 long int size = ftell(fp);
2030
2031 fseek(fp, 0L, SEEK_SET);
2032
2033 void *shader_code = malloc(size);
2034 size_t retval = fread(shader_code, size, 1, fp);
2035 VERIFY(retval == 1);
2036
2037 *psize = size;
2038
2039 fclose(fp);
2040
2041 return (char*)shader_code;
2042 }
2043
2044 void resize()
2045 {
2046 uint32_t i;
2047
2048 // Don't react to resize until after first initialization.
2049 if(!prepared)
2050 {
2051 return;
2052 }
2053
2054 // In order to properly resize the window, we must re-create the swapchain
2055 // AND redo the command buffers, etc.
2056 //
2057 // First, perform part of the cleanup() function:
2058 prepared = false;
2059 auto result = device.waitIdle();
2060 VERIFY(result == vk::Result::eSuccess);
2061
2062 for(i = 0; i < swapchainImageCount; i++)
2063 {
2064 device.destroyFramebuffer(framebuffers[i], nullptr);
2065 }
2066
2067 device.destroyDescriptorPool(desc_pool, nullptr);
2068
2069 device.destroyPipeline(pipeline, nullptr);
2070 device.destroyPipelineCache(pipelineCache, nullptr);
2071 device.destroyRenderPass(render_pass, nullptr);
2072 device.destroyPipelineLayout(pipeline_layout, nullptr);
2073 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2074
2075 for(i = 0; i < texture_count; i++)
2076 {
2077 device.destroyImageView(textures[i].view, nullptr);
2078 device.destroyImage(textures[i].image, nullptr);
2079 device.freeMemory(textures[i].mem, nullptr);
2080 device.destroySampler(textures[i].sampler, nullptr);
2081 }
2082
2083 device.destroyImageView(depth.view, nullptr);
2084 device.destroyImage(depth.image, nullptr);
2085 device.freeMemory(depth.mem, nullptr);
2086
2087 device.destroyBuffer(uniform_data.buf, nullptr);
2088 device.freeMemory(uniform_data.mem, nullptr);
2089
2090 for(i = 0; i < swapchainImageCount; i++)
2091 {
2092 device.destroyImageView(buffers[i].view, nullptr);
2093 device.freeCommandBuffers(cmd_pool, 1, &buffers[i].cmd);
2094 }
2095
2096 device.destroyCommandPool(cmd_pool, nullptr);
2097 if(separate_present_queue)
2098 {
2099 device.destroyCommandPool(present_cmd_pool, nullptr);
2100 }
2101
2102 // Second, re-perform the prepare() function, which will re-create the swapchain.
2103 prepare();
2104 }
2105
2106 void set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout,
2107 vk::ImageLayout newLayout, vk::AccessFlags srcAccessMask)
2108 {
2109 if(!cmd)
2110 {
2111 auto const cmd = vk::CommandBufferAllocateInfo()
2112 .setCommandPool(cmd_pool)
2113 .setLevel(vk::CommandBufferLevel::ePrimary)
2114 .setCommandBufferCount(1);
2115
2116 auto result = device.allocateCommandBuffers(&cmd, &this->cmd);
2117 VERIFY(result == vk::Result::eSuccess);
2118
2119 auto const cmd_buf_info = vk::CommandBufferBeginInfo()
2120 .setPInheritanceInfo(nullptr);
2121
2122 result = this->cmd.begin(&cmd_buf_info);
2123 VERIFY(result == vk::Result::eSuccess);
2124 }
2125
2126 auto DstAccessMask = [](vk::ImageLayout const& layout)
2127 {
2128 vk::AccessFlags flags;
2129
2130 switch(layout)
2131 {
2132 case vk::ImageLayout::eTransferDstOptimal:
2133 // Make sure anything that was copying from this image has completed
2134 flags = vk::AccessFlagBits::eTransferRead;
2135 break;
2136 case vk::ImageLayout::eColorAttachmentOptimal:
2137 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2138 break;
2139 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2140 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2141 break;
2142 case vk::ImageLayout::eShaderReadOnlyOptimal:
2143 // Make sure any Copy or CPU writes to image are flushed
2144 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2145 break;
2146 case vk::ImageLayout::ePresentSrcKHR:
2147 flags = vk::AccessFlagBits::eMemoryRead;
2148 break;
2149 default:
2150 break;
2151 }
2152
2153 return flags;
2154 };
2155
2156 auto const barrier = vk::ImageMemoryBarrier()
2157 .setSrcAccessMask(srcAccessMask)
2158 .setDstAccessMask(DstAccessMask(newLayout))
2159 .setOldLayout(oldLayout)
2160 .setNewLayout(newLayout)
2161 .setSrcQueueFamilyIndex(0)
2162 .setDstQueueFamilyIndex(0)
2163 .setImage(image)
2164 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2165
2166 cmd.pipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTopOfPipe, vk::DependencyFlagBits(),
2167 0, nullptr, 0, nullptr, 1, &barrier);
2168 }
2169
2170 void update_data_buffer()
2171 {
2172 mat4x4 VP;
2173 mat4x4_mul(VP, projection_matrix, view_matrix);
2174
2175 // Rotate 22.5 degrees around the Y axis
2176 mat4x4 Model;
2177 mat4x4_dup(Model, model_matrix);
2178 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2179
2180 mat4x4 MVP;
2181 mat4x4_mul(MVP, VP, model_matrix);
2182
2183 auto data = device.mapMemory(uniform_data.mem, 0, uniform_data.mem_alloc.allocationSize, vk::MemoryMapFlags());
2184 VERIFY(data.result == vk::Result::eSuccess);
2185
2186 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2187
2188 device.unmapMemory(uniform_data.mem);
2189 }
2190
2191 bool loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height)
2192 {
2193 FILE *fPtr = fopen(filename, "rb");
2194 if(!fPtr)
2195 {
2196 return false;
2197 }
2198
2199 char header[256];
2200 char* cPtr = fgets(header, 256, fPtr); // P6
2201 if(cPtr == nullptr || strncmp(header, "P6\n", 3))
2202 {
2203 fclose(fPtr);
2204 return false;
2205 }
2206
2207 do
2208 {
2209 cPtr = fgets(header, 256, fPtr);
2210 if(cPtr == nullptr)
2211 {
2212 fclose(fPtr);
2213 return false;
2214 }
2215 }
2216 while(!strncmp(header, "#", 1));
2217
2218 sscanf(header, "%u %u", width, height);
2219 if(rgba_data == nullptr)
2220 {
2221 fclose(fPtr);
2222 return true;
2223 }
2224
2225 char* result = fgets(header, 256, fPtr); // Format
2226 VERIFY(result != nullptr);
2227 if(cPtr == nullptr || strncmp(header, "255\n", 3))
2228 {
2229 fclose(fPtr);
2230 return false;
2231 }
2232
2233 for(int y = 0; y < *height; y++)
2234 {
2235 uint8_t *rowPtr = rgba_data;
2236
2237 for(int x = 0; x < *width; x++)
2238 {
2239 size_t s = fread(rowPtr, 3, 1, fPtr);
2240 (void)s;
2241 rowPtr[3] = 255; /* Alpha of 1 */
2242 rowPtr += 4;
2243 }
2244
2245 rgba_data += layout->rowPitch;
2246 }
2247
2248 fclose(fPtr);
2249 return true;
2250 }
2251
2252 bool memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex)
2253 {
2254 // Search memtypes to find first index with those properties
2255 for(uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++)
2256 {
2257 if((typeBits & 1) == 1)
2258 {
2259 // Type is available, does it match user properties?
2260 if((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask)
2261 {
2262 *typeIndex = i;
2263 return true;
2264 }
2265 }
2266 typeBits >>= 1;
2267 }
2268
2269 // No memory types matched, return failure
2270 return false;
2271 }
2272
2273#if defined(VK_USE_PLATFORM_WIN32_KHR)
2274 void run()
2275 {
2276 if(!prepared)
2277 {
2278 return;
2279 }
2280
2281 update_data_buffer();
2282 draw();
2283 curFrame++;
2284
2285 if(frameCount != INT_MAX && curFrame == frameCount)
2286 {
2287 PostQuitMessage(validation_error);
2288 }
2289 }
2290
2291 void create_window()
2292 {
2293 WNDCLASSEX win_class;
2294
2295 // Initialize the window class structure:
2296 win_class.cbSize = sizeof(WNDCLASSEX);
2297 win_class.style = CS_HREDRAW | CS_VREDRAW;
2298 win_class.lpfnWndProc = WndProc;
2299 win_class.cbClsExtra = 0;
2300 win_class.cbWndExtra = 0;
2301 win_class.hInstance = connection; // hInstance
2302 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2303 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2304 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2305 win_class.lpszMenuName = nullptr;
2306 win_class.lpszClassName = name;
2307 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2308
2309 // Register window class:
2310 if(!RegisterClassEx(&win_class))
2311 {
2312 // It didn't work, so try to give a useful error:
2313 printf("Unexpected error trying to start the application!\n");
2314 fflush(stdout);
2315 exit(1);
2316 }
2317
2318 // Create window with the registered class:
2319 RECT wr = {0, 0, width, height};
2320 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2321 window = CreateWindowEx(0,
2322 name, // class name
2323 name, // app name
2324 WS_OVERLAPPEDWINDOW | // window style
2325 WS_VISIBLE | WS_SYSMENU,
2326 100, 100, // x/y coords
2327 wr.right - wr.left, // width
2328 wr.bottom - wr.top, // height
2329 nullptr, // handle to parent
2330 nullptr, // handle to menu
2331 connection, // hInstance
2332 nullptr); // no extra parameters
2333
2334 if(!window)
2335 {
2336 // It didn't work, so try to give a useful error:
2337 printf("Cannot create a window in which to draw!\n");
2338 fflush(stdout);
2339 exit(1);
2340 }
2341
2342 // Window client area size must be at least 1 pixel high, to prevent crash.
2343 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2344 minsize.y = GetSystemMetrics(SM_CYMINTRACK)+1;
2345 }
2346
2347#elif defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
2348#if defined(VK_USE_PLATFORM_XLIB_KHR)
2349
2350 void create_xlib_window()
2351 {
2352 display = XOpenDisplay(nullptr);
2353 long visualMask = VisualScreenMask;
2354 int numberOfVisuals;
2355 XVisualInfo vInfoTemplate={};
2356 vInfoTemplate.screen = DefaultScreen(display);
2357 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2358
2359 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2360
2361 XSetWindowAttributes windowAttributes={};
2362 windowAttributes.colormap = colormap;
2363 windowAttributes.background_pixel = 0xFFFFFFFF;
2364 windowAttributes.border_pixel = 0;
2365 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2366
2367 xlib_window = XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height,
2368 0, visualInfo->depth, InputOutput, visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap,
2369 &windowAttributes);
2370
2371 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2372 XMapWindow(display, xlib_window);
2373 XFlush(display);
2374 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2375 }
2376
2377 void handle_xlib_event(const XEvent *event)
2378 {
2379 switch(event->type)
2380 {
2381 case ClientMessage:
2382 if((Atom)event->xclient.data.l[0] == xlib_wm_delete_window)
2383 {
2384 quit = true;
2385 }
2386 break;
2387 case KeyPress:
2388 switch (event->xkey.keycode)
2389 {
2390 case 0x9: // Escape
2391 quit = true;
2392 break;
2393 case 0x71: // left arrow key
2394 spin_angle += spin_increment;
2395 break;
2396 case 0x72: // right arrow key
2397 spin_angle -= spin_increment;
2398 break;
2399 case 0x41:
2400 pause = !pause;
2401 break;
2402 }
2403 break;
2404 case ConfigureNotify:
2405 if(((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height))
2406 {
2407 width = event->xconfigure.width;
2408 height = event->xconfigure.height;
2409 resize();
2410 }
2411 break;
2412 default:
2413 break;
2414 }
2415 }
2416
2417 void run_xlib()
2418 {
2419 while(!quit)
2420 {
2421 XEvent event;
2422
2423 if(pause)
2424 {
2425 XNextEvent(display, &event);
2426 handle_xlib_event(&event);
2427 }
2428 else
2429 {
2430 while(XPending(display) > 0)
2431 {
2432 XNextEvent(display, &event);
2433 handle_xlib_event(&event);
2434 }
2435 }
2436
2437 update_data_buffer();
2438 draw();
2439 curFrame++;
2440
2441 if(frameCount != UINT32_MAX && curFrame == frameCount)
2442 {
2443 quit = true;
2444 }
2445 }
2446 }
2447
2448#endif
2449#if defined(VK_USE_PLATFORM_XCB_KHR)
2450
2451 void handle_xcb_event(const xcb_generic_event_t *event)
2452 {
2453 uint8_t event_code = event->response_type & 0x7f;
2454 switch(event_code)
2455 {
2456 case XCB_EXPOSE:
2457 // TODO: Resize window
2458 break;
2459 case XCB_CLIENT_MESSAGE:
2460 if((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom)
2461 {
2462 quit = true;
2463 }
2464 break;
2465 case XCB_KEY_RELEASE:
2466 {
2467 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2468
2469 switch(key->detail)
2470 {
2471 case 0x9: // Escape
2472 quit = true;
2473 break;
2474 case 0x71: // left arrow key
2475 spin_angle += spin_increment;
2476 break;
2477 case 0x72: // right arrow key
2478 spin_angle -= spin_increment;
2479 break;
2480 case 0x41:
2481 pause = !pause;
2482 break;
2483 }
2484 } break;
2485 case XCB_CONFIGURE_NOTIFY:
2486 {
2487 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2488 if((width != cfg->width) || (height != cfg->height))
2489 {
2490 width = cfg->width;
2491 height = cfg->height;
2492 resize();
2493 }
2494 } break;
2495 default:
2496 break;
2497 }
2498 }
2499
2500 void run_xcb()
2501 {
2502 xcb_flush(connection);
2503
2504 while(!quit)
2505 {
2506 xcb_generic_event_t *event;
2507
2508 if(pause)
2509 {
2510 event = xcb_wait_for_event(connection);
2511 }
2512 else
2513 {
2514 event = xcb_poll_for_event(connection);
2515 while(event)
2516 {
2517 handle_xcb_event(event);
2518 free(event);
2519 event = xcb_poll_for_event(connection);
2520 }
2521 }
2522
2523 update_data_buffer();
2524 draw();
2525 curFrame++;
2526 if(frameCount != UINT32_MAX && curFrame == frameCount)
2527 {
2528 quit = true;
2529 }
2530 }
2531 }
2532
2533 void create_xcb_window()
2534 {
2535 uint32_t value_mask, value_list[32];
2536
2537 xcb_window = xcb_generate_id(connection);
2538
2539 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2540 value_list[0] = screen->black_pixel;
2541 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2542
2543 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2544 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2545
2546 /* Magic code that will send notification when window is destroyed */
2547 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2548 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2549
2550 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2551 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2552
2553 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1,
2554 &(*atom_wm_delete_window).atom);
2555
2556 free(reply);
2557
2558 xcb_map_window(connection, xcb_window);
2559
2560 // Force the x/y coordinates to 100,100 results are identical in consecutive
2561 // runs
2562 const uint32_t coords[] = {100, 100};
2563 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2564 }
2565
2566#endif
2567#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2568
2569 void run()
2570 {
2571 while (!quit)
2572 {
2573 update_data_buffer();
2574 draw();
2575 curFrame++;
2576 if(frameCount != UINT32_MAX && curFrame == frameCount)
2577 {
2578 quit = true;
2579 }
2580 }
2581 }
2582
2583 void create_window()
2584 {
2585 window = wl_compositor_create_surface(compositor);
2586 if(!window)
2587 {
2588 printf("Can not create wayland_surface from compositor!\n");
2589 fflush(stdout);
2590 exit(1);
2591 }
2592
2593 shell_surface = wl_shell_get_shell_surface(shell, window);
2594 if(!shell_surface)
2595 {
2596 printf("Can not get shell_surface from wayland_surface!\n");
2597 fflush(stdout);
2598 exit(1);
2599 }
2600
2601 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2602 wl_shell_surface_set_toplevel(shell_surface);
2603 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
2604 }
2605
2606#endif
2607
2608#if defined(VK_USE_PLATFORM_WIN32_KHR)
2609 HINSTANCE connection; // hInstance - Windows Instance
2610 HWND window; // hWnd - window handle
2611 POINT minsize; // minimum window size
2612 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
2613#elif defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
2614 Display* display;
2615 Window xlib_window;
2616 Atom xlib_wm_delete_window;
2617
2618 xcb_connection_t *connection;
2619 xcb_screen_t *screen;
2620 xcb_window_t xcb_window;
2621 xcb_intern_atom_reply_t *atom_wm_delete_window;
2622#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2623 wl_display *display;
2624 wl_registry *registry;
2625 wl_compositor *compositor;
2626 wl_surface *window;
2627 wl_shell *shell;
2628 wl_shell_surface *shell_surface;
2629#endif
2630
2631 vk::SurfaceKHR surface;
2632 bool prepared;
2633 bool use_staging_buffer;
2634 bool use_xlib;
2635 bool separate_present_queue;
2636
2637 vk::Instance inst;
2638 vk::PhysicalDevice gpu;
2639 vk::Device device;
2640 vk::Queue graphics_queue;
2641 vk::Queue present_queue;
2642 uint32_t graphics_queue_family_index;
2643 uint32_t present_queue_family_index;
2644 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
2645 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
2646 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
2647 vk::PhysicalDeviceProperties gpu_props;
2648 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
2649 vk::PhysicalDeviceMemoryProperties memory_properties;
2650
2651 uint32_t enabled_extension_count;
2652 uint32_t enabled_layer_count;
2653 char const* extension_names[64];
2654 char const* enabled_layers[64];
2655
2656 uint32_t width;
2657 uint32_t height;
2658 vk::Format format;
2659 vk::ColorSpaceKHR color_space;
2660
2661 uint32_t swapchainImageCount;
2662 vk::SwapchainKHR swapchain;
2663 std::unique_ptr<SwapchainBuffers[]> buffers;
2664 vk::Fence fences[FRAME_LAG];
2665 bool fencesInited[FRAME_LAG];
2666 uint32_t frame_index;
2667
2668 vk::CommandPool cmd_pool;
2669 vk::CommandPool present_cmd_pool;
2670
2671 struct
2672 {
2673 vk::Format format;
2674 vk::Image image;
2675 vk::MemoryAllocateInfo mem_alloc;
2676 vk::DeviceMemory mem;
2677 vk::ImageView view;
2678 } depth;
2679
2680 static int32_t const texture_count = 1;
2681 texture_object textures[texture_count];
2682
2683 struct
2684 {
2685 vk::Buffer buf;
2686 vk::MemoryAllocateInfo mem_alloc;
2687 vk::DeviceMemory mem;
2688 vk::DescriptorBufferInfo buffer_info;
2689 } uniform_data;
2690
2691 vk::CommandBuffer cmd; // Buffer for initialization commands
2692 vk::PipelineLayout pipeline_layout;
2693 vk::DescriptorSetLayout desc_layout;
2694 vk::PipelineCache pipelineCache;
2695 vk::RenderPass render_pass;
2696 vk::Pipeline pipeline;
2697
2698 mat4x4 projection_matrix;
2699 mat4x4 view_matrix;
2700 mat4x4 model_matrix;
2701
2702 float spin_angle;
2703 float spin_increment;
2704 bool pause;
2705
2706 vk::ShaderModule vert_shader_module;
2707 vk::ShaderModule frag_shader_module;
2708
2709 vk::DescriptorPool desc_pool;
2710 vk::DescriptorSet desc_set;
2711
2712 std::unique_ptr<vk::Framebuffer[]> framebuffers;
2713
2714 bool quit;
2715 uint32_t curFrame;
2716 uint32_t frameCount;
2717 bool validate;
2718 bool use_break;
2719 bool suppress_popups;
2720
2721 uint32_t current_buffer;
2722 uint32_t queue_family_count;
2723};
2724
2725#if _WIN32
2726// Include header required for parsing the command line options.
2727#include <shellapi.h>
2728
2729Demo demo;
2730
2731// MS-Windows event handling function:
2732LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
2733{
2734 switch (uMsg)
2735 {
2736 case WM_CLOSE:
2737 PostQuitMessage(validation_error);
2738 break;
2739 case WM_PAINT:
2740 demo.run();
2741 break;
2742 case WM_GETMINMAXINFO: // set window's minimum size
2743 ((MINMAXINFO*)lParam)->ptMinTrackSize = demo.minsize;
2744 return 0;
2745 case WM_SIZE:
2746 // Resize the application to the new window size, except when
2747 // it was minimized. Vulkan doesn't support images or swapchains
2748 // with width=0 and height=0.
2749 if(wParam != SIZE_MINIMIZED) {
2750 demo.width = lParam & 0xffff;
2751 demo.height = (lParam & 0xffff0000) >> 16;
2752 demo.resize();
2753 }
2754 break;
2755 default:
2756 break;
2757 }
2758
2759 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2760}
2761
2762int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow)
2763{
2764 // TODO: Gah.. refactor. This isn't 1989.
2765 MSG msg; // message
2766 bool done; // flag saying when app is complete
2767 int argc;
2768 char **argv;
2769
2770 // Use the CommandLine functions to get the command line arguments.
2771 // Unfortunately, Microsoft outputs
2772 // this information as wide characters for Unicode, and we simply want the
2773 // Ascii version to be compatible
2774 // with the non-Windows side. So, we have to convert the information to
2775 // Ascii character strings.
2776 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
2777 if(nullptr == commandLineArgs)
2778 {
2779 argc = 0;
2780 }
2781
2782 if(argc > 0)
2783 {
2784 argv = (char **)malloc(sizeof(char *) * argc);
2785 if(argv == nullptr)
2786 {
2787 argc = 0;
2788 }
2789 else
2790 {
2791 for(int iii = 0; iii < argc; iii++)
2792 {
2793 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2794 size_t numConverted = 0;
2795
2796 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
2797 if(argv[iii] != nullptr)
2798 {
2799 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
2800 }
2801 }
2802 }
2803 }
2804 else
2805 {
2806 argv = nullptr;
2807 }
2808
2809 demo.init(argc, argv);
2810
2811 // Free up the items we had to allocate for the command line arguments.
2812 if(argc > 0 && argv != nullptr)
2813 {
2814 for(int iii = 0; iii < argc; iii++)
2815 {
2816 if(argv[iii] != nullptr)
2817 {
2818 free(argv[iii]);
2819 }
2820 }
2821 free(argv);
2822 }
2823
2824 demo.connection = hInstance;
2825 strncpy(demo.name, "cube", APP_NAME_STR_LEN);
2826 demo.create_window();
2827 demo.init_vk_swapchain();
2828
2829 demo.prepare();
2830
2831 done = false; // initialize loop condition variable
2832
2833 // main message loop
2834 while(!done)
2835 {
2836 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
2837 if(msg.message == WM_QUIT) // check for a quit message
2838 {
2839 done = true; // if found, quit app
2840 }
2841 else
2842 {
2843 /* Translate and dispatch to event queue*/
2844 TranslateMessage(&msg);
2845 DispatchMessage(&msg);
2846 }
2847 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2848 }
2849
2850 demo.cleanup();
2851
2852 return (int)msg.wParam;
2853}
2854
2855#elif __linux__
2856
2857#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
2858static void handle_ping(void *data UNUSED, wl_shell_surface *shell_surface, uint32_t serial)
2859{
2860 wl_shell_surface_pong(shell_surface, serial);
2861}
2862
2863static void handle_configure(void *data UNUSED, wl_shell_surface *shell_surface UNUSED, uint32_t edges UNUSED,
2864 int32_t width UNUSED, int32_t height UNUSED)
2865{
2866}
2867
2868static void handle_popup_done(void *data UNUSED, wl_shell_surface *shell_surface UNUSED)
2869{
2870}
2871
2872static const wl_shell_surface_listener shell_surface_listener =
2873{
2874 handle_ping,
2875 handle_configure,
2876 handle_popup_done
2877};
2878#endif
2879
2880int main(int argc, char **argv)
2881{
2882 Demo demo;
2883
2884 demo.init(argc, argv);
2885
2886#if defined(VK_USE_PLATFORM_XLIB_KHR) && defined(VK_USE_PLATFORM_XCB_KHR)
2887 if(demo.use_xlib)
2888 {
2889 demo.create_xlib_window();
2890 }
2891 else
2892 {
2893 demo.create_xcb_window();
2894#elif defined(VK_USE_PLATFORM_XCB_KHR)
2895 demo.create_xcb_window();
2896#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2897 demo.create_xlib_window();
2898#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2899 demo.create_window();
2900#endif
2901 }
2902
2903 demo.init_vk_swapchain();
2904
2905 demo.prepare();
2906
2907#if defined(VK_USE_PLATFORM_XLIB_KHR) && defined(VK_USE_PLATFORM_XCB_KHR)
2908 if(demo.use_xlib)
2909 {
2910 demo.run_xlib();
2911 }
2912 else
2913 {
2914 demo.run_xcb();
2915#elif defined(VK_USE_PLATFORM_XCB_KHR)
2916 demo.run_xcb();
2917#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2918 demo.run_xlib();
2919#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2920 demo.run();
2921#endif
2922 }
2923
2924 demo.cleanup();
2925
2926 return validation_error;
2927}
2928
2929#else
2930#error "Platform not supported"
2931#endif