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