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