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