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