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