blob: 216440ab14b8a94c227f76eb67969f370b53d8a6 [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;
Tony-LunarG37af49f2019-12-19 12:04:19 -0700209 void *uniform_memory_ptr;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600210 vk::Framebuffer framebuffer;
211 vk::DescriptorSet descriptor_set;
212} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600213
Joey Bzdekbaf66472017-06-07 09:37:37 -0600214struct Demo {
215 Demo();
216 void build_image_ownership_cmd(uint32_t const &);
217 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
218 void cleanup();
219 void create_device();
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600220 void destroy_texture(texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600221 void draw();
222 void draw_build_cmd(vk::CommandBuffer);
223 void flush_init_cmd();
224 void init(int, char **);
225 void init_connection();
226 void init_vk();
227 void init_vk_swapchain();
228 void prepare();
229 void prepare_buffers();
230 void prepare_cube_data_buffers();
231 void prepare_depth();
232 void prepare_descriptor_layout();
233 void prepare_descriptor_pool();
234 void prepare_descriptor_set();
235 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100236 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
237 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600238 vk::ShaderModule prepare_fs();
239 void prepare_pipeline();
240 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600241 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600242 void prepare_texture_buffer(const char *, texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600243 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100244
Joey Bzdekbaf66472017-06-07 09:37:37 -0600245 void resize();
Tony-LunarG6cebf142019-09-11 14:32:23 -0600246 void create_surface();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600247 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
248 vk::PipelineStageFlags, vk::PipelineStageFlags);
249 void update_data_buffer();
250 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
251 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
252
253#if defined(VK_USE_PLATFORM_WIN32_KHR)
254 void run();
255 void create_window();
256#elif defined(VK_USE_PLATFORM_XLIB_KHR)
257 void create_xlib_window();
258 void handle_xlib_event(const XEvent *);
259 void run_xlib();
260#elif defined(VK_USE_PLATFORM_XCB_KHR)
261 void handle_xcb_event(const xcb_generic_event_t *);
262 void run_xcb();
263 void create_xcb_window();
264#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
265 void run();
266 void create_window();
Bill Hollings0a0625a2019-07-15 17:39:18 -0400267#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -0600268 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600269#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
270 vk::Result create_display_surface();
271 void run_display();
272#endif
273
274#if defined(VK_USE_PLATFORM_WIN32_KHR)
275 HINSTANCE connection; // hInstance - Windows Instance
276 HWND window; // hWnd - window handle
277 POINT minsize; // minimum window size
278 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
279#elif defined(VK_USE_PLATFORM_XLIB_KHR)
280 Window xlib_window;
281 Atom xlib_wm_delete_window;
282 Display *display;
283#elif defined(VK_USE_PLATFORM_XCB_KHR)
284 xcb_window_t xcb_window;
285 xcb_screen_t *screen;
286 xcb_connection_t *connection;
287 xcb_intern_atom_reply_t *atom_wm_delete_window;
288#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
289 wl_display *display;
290 wl_registry *registry;
291 wl_compositor *compositor;
292 wl_surface *window;
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700293 wl_shell *shell;
294 wl_shell_surface *shell_surface;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600295 wl_seat *seat;
296 wl_pointer *pointer;
297 wl_keyboard *keyboard;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400298#elif defined(VK_USE_PLATFORM_METAL_EXT)
299 void *caMetalLayer;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600300#endif
301
302 vk::SurfaceKHR surface;
303 bool prepared;
304 bool use_staging_buffer;
305 bool use_xlib;
306 bool separate_present_queue;
307
308 vk::Instance inst;
309 vk::PhysicalDevice gpu;
310 vk::Device device;
311 vk::Queue graphics_queue;
312 vk::Queue present_queue;
313 uint32_t graphics_queue_family_index;
314 uint32_t present_queue_family_index;
315 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
316 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
317 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
318 vk::PhysicalDeviceProperties gpu_props;
319 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
320 vk::PhysicalDeviceMemoryProperties memory_properties;
321
322 uint32_t enabled_extension_count;
323 uint32_t enabled_layer_count;
324 char const *extension_names[64];
325 char const *enabled_layers[64];
326
327 uint32_t width;
328 uint32_t height;
329 vk::Format format;
330 vk::ColorSpaceKHR color_space;
331
332 uint32_t swapchainImageCount;
333 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600334 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600335 vk::PresentModeKHR presentMode;
336 vk::Fence fences[FRAME_LAG];
337 uint32_t frame_index;
338
339 vk::CommandPool cmd_pool;
340 vk::CommandPool present_cmd_pool;
341
342 struct {
343 vk::Format format;
344 vk::Image image;
345 vk::MemoryAllocateInfo mem_alloc;
346 vk::DeviceMemory mem;
347 vk::ImageView view;
348 } depth;
349
350 static int32_t const texture_count = 1;
351 texture_object textures[texture_count];
352 texture_object staging_texture;
353
354 struct {
355 vk::Buffer buf;
356 vk::MemoryAllocateInfo mem_alloc;
357 vk::DeviceMemory mem;
358 vk::DescriptorBufferInfo buffer_info;
359 } uniform_data;
360
361 vk::CommandBuffer cmd; // Buffer for initialization commands
362 vk::PipelineLayout pipeline_layout;
363 vk::DescriptorSetLayout desc_layout;
364 vk::PipelineCache pipelineCache;
365 vk::RenderPass render_pass;
366 vk::Pipeline pipeline;
367
368 mat4x4 projection_matrix;
369 mat4x4 view_matrix;
370 mat4x4 model_matrix;
371
372 float spin_angle;
373 float spin_increment;
374 bool pause;
375
376 vk::ShaderModule vert_shader_module;
377 vk::ShaderModule frag_shader_module;
378
379 vk::DescriptorPool desc_pool;
380 vk::DescriptorSet desc_set;
381
382 std::unique_ptr<vk::Framebuffer[]> framebuffers;
383
384 bool quit;
385 uint32_t curFrame;
386 uint32_t frameCount;
387 bool validate;
388 bool use_break;
389 bool suppress_popups;
390
391 uint32_t current_buffer;
392 uint32_t queue_family_count;
393};
394
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600395#ifdef _WIN32
396// MS-Windows event handling function:
397LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
398#endif
399
Karl Schultz23cc2182016-11-23 17:15:17 -0700400#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700401static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700402 wl_shell_surface_pong(shell_surface, serial);
403}
404
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700405static 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 -0700406
407static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
408
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700409static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700410
Joey Bzdek15eb0702017-06-07 09:40:36 -0600411static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
412 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700413
Joey Bzdek15eb0702017-06-07 09:40:36 -0600414static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700415
Joey Bzdek15eb0702017-06-07 09:40:36 -0600416static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
417
418static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
419 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600420 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600421 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700422 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600423 }
424}
425
426static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
427
428static const struct wl_pointer_listener pointer_listener = {
429 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
430};
431
432static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
433
434static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
435 struct wl_array *keys) {}
436
437static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
438
439static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
440 uint32_t state) {
441 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
442 Demo *demo = (Demo *)data;
443 switch (key) {
444 case KEY_ESC: // Escape
445 demo->quit = true;
446 break;
447 case KEY_LEFT: // left arrow key
448 demo->spin_angle -= demo->spin_increment;
449 break;
450 case KEY_RIGHT: // right arrow key
451 demo->spin_angle += demo->spin_increment;
452 break;
453 case KEY_SPACE: // space bar
454 demo->pause = !demo->pause;
455 break;
456 }
457}
458
459static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
460 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
461
462static const struct wl_keyboard_listener keyboard_listener = {
463 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
464};
465
466static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
467 // Subscribe to pointer events
468 Demo *demo = (Demo *)data;
469 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
470 demo->pointer = wl_seat_get_pointer(seat);
471 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
472 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
473 wl_pointer_destroy(demo->pointer);
474 demo->pointer = NULL;
475 }
476 // Subscribe to keyboard events
477 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
478 demo->keyboard = wl_seat_get_keyboard(seat);
479 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
480 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
481 wl_keyboard_destroy(demo->keyboard);
482 demo->keyboard = NULL;
483 }
484}
485
486static const wl_seat_listener seat_listener = {
487 seat_handle_capabilities,
488};
489
490static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
491 Demo *demo = (Demo *)data;
492 // pickup wayland objects when they appear
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700493 if (strcmp(interface, "wl_compositor") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600494 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700495 } else if (strcmp(interface, "wl_shell") == 0) {
496 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
497 } else if (strcmp(interface, "wl_seat") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600498 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
499 wl_seat_add_listener(demo->seat, &seat_listener, demo);
500 }
501}
502
503static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
504
505static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700506#endif
507
Joey Bzdekbaf66472017-06-07 09:37:37 -0600508Demo::Demo()
509 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600510#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600511 connection{nullptr},
512 window{nullptr},
513 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600514#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700515
Tony Barbour78d6b572016-11-14 14:46:33 -0700516#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600517 xlib_window{0},
518 xlib_wm_delete_window{0},
519 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700520#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600521 xcb_window{0},
522 screen{nullptr},
523 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700524#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600525 display{nullptr},
526 registry{nullptr},
527 compositor{nullptr},
528 window{nullptr},
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700529 shell{nullptr},
530 shell_surface{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600531 seat{nullptr},
532 pointer{nullptr},
533 keyboard{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700534#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600535 prepared{false},
536 use_staging_buffer{false},
537 use_xlib{false},
538 graphics_queue_family_index{0},
539 present_queue_family_index{0},
540 enabled_extension_count{0},
541 enabled_layer_count{0},
542 width{0},
543 height{0},
544 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000545 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600546 frame_index{0},
547 spin_angle{0.0f},
548 spin_increment{0.0f},
549 pause{false},
550 quit{false},
551 curFrame{0},
552 frameCount{0},
553 validate{false},
554 use_break{false},
555 suppress_popups{false},
556 current_buffer{0},
557 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600558#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700559 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600560#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700561 memset(projection_matrix, 0, sizeof(projection_matrix));
562 memset(view_matrix, 0, sizeof(view_matrix));
563 memset(model_matrix, 0, sizeof(model_matrix));
564}
565
566void Demo::build_image_ownership_cmd(uint32_t const &i) {
567 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
568 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
569 VERIFY(result == vk::Result::eSuccess);
570
571 auto const image_ownership_barrier =
572 vk::ImageMemoryBarrier()
573 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600574 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700575 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
576 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
577 .setSrcQueueFamilyIndex(graphics_queue_family_index)
578 .setDstQueueFamilyIndex(present_queue_family_index)
579 .setImage(swapchain_image_resources[i].image)
580 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
581
582 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600583 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
584 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700585
586 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
587 VERIFY(result == vk::Result::eSuccess);
588}
589
590vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
591 vk::LayerProperties *layers) {
592 for (uint32_t i = 0; i < check_count; i++) {
593 vk::Bool32 found = VK_FALSE;
594 for (uint32_t j = 0; j < layer_count; j++) {
595 if (!strcmp(check_names[i], layers[j].layerName)) {
596 found = VK_TRUE;
597 break;
598 }
599 }
600 if (!found) {
601 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
602 return 0;
603 }
604 }
605 return VK_TRUE;
606}
607
608void Demo::cleanup() {
609 prepared = false;
610 device.waitIdle();
611
612 // Wait for fences from present operations
613 for (uint32_t i = 0; i < FRAME_LAG; i++) {
614 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
615 device.destroyFence(fences[i], nullptr);
616 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
617 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
618 if (separate_present_queue) {
619 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
620 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600621 }
622
Dave Houlton5fa47912018-02-16 11:02:26 -0700623 for (uint32_t i = 0; i < swapchainImageCount; i++) {
624 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
625 }
626 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600627
Dave Houlton5fa47912018-02-16 11:02:26 -0700628 device.destroyPipeline(pipeline, nullptr);
629 device.destroyPipelineCache(pipelineCache, nullptr);
630 device.destroyRenderPass(render_pass, nullptr);
631 device.destroyPipelineLayout(pipeline_layout, nullptr);
632 device.destroyDescriptorSetLayout(desc_layout, nullptr);
633
634 for (uint32_t i = 0; i < texture_count; i++) {
635 device.destroyImageView(textures[i].view, nullptr);
636 device.destroyImage(textures[i].image, nullptr);
637 device.freeMemory(textures[i].mem, nullptr);
638 device.destroySampler(textures[i].sampler, nullptr);
639 }
640 device.destroySwapchainKHR(swapchain, nullptr);
641
642 device.destroyImageView(depth.view, nullptr);
643 device.destroyImage(depth.image, nullptr);
644 device.freeMemory(depth.mem, nullptr);
645
646 for (uint32_t i = 0; i < swapchainImageCount; i++) {
647 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
648 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
649 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700650 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700651 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
652 }
653
654 device.destroyCommandPool(cmd_pool, nullptr);
655
656 if (separate_present_queue) {
657 device.destroyCommandPool(present_cmd_pool, nullptr);
658 }
659 device.waitIdle();
660 device.destroy(nullptr);
661 inst.destroySurfaceKHR(surface, nullptr);
662
663#if defined(VK_USE_PLATFORM_XLIB_KHR)
664 XDestroyWindow(display, xlib_window);
665 XCloseDisplay(display);
666#elif defined(VK_USE_PLATFORM_XCB_KHR)
667 xcb_destroy_window(connection, xcb_window);
668 xcb_disconnect(connection);
669 free(atom_wm_delete_window);
670#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
671 wl_keyboard_destroy(keyboard);
672 wl_pointer_destroy(pointer);
673 wl_seat_destroy(seat);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700674 wl_shell_surface_destroy(shell_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700675 wl_surface_destroy(window);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700676 wl_shell_destroy(shell);
Dave Houlton5fa47912018-02-16 11:02:26 -0700677 wl_compositor_destroy(compositor);
678 wl_registry_destroy(registry);
679 wl_display_disconnect(display);
Dave Houlton5fa47912018-02-16 11:02:26 -0700680#endif
681
682 inst.destroy(nullptr);
683}
684
685void Demo::create_device() {
686 float const priorities[1] = {0.0};
687
688 vk::DeviceQueueCreateInfo queues[2];
689 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
690 queues[0].setQueueCount(1);
691 queues[0].setPQueuePriorities(priorities);
692
693 auto deviceInfo = vk::DeviceCreateInfo()
694 .setQueueCreateInfoCount(1)
695 .setPQueueCreateInfos(queues)
696 .setEnabledLayerCount(0)
697 .setPpEnabledLayerNames(nullptr)
698 .setEnabledExtensionCount(enabled_extension_count)
699 .setPpEnabledExtensionNames((const char *const *)extension_names)
700 .setPEnabledFeatures(nullptr);
701
702 if (separate_present_queue) {
703 queues[1].setQueueFamilyIndex(present_queue_family_index);
704 queues[1].setQueueCount(1);
705 queues[1].setPQueuePriorities(priorities);
706 deviceInfo.setQueueCreateInfoCount(2);
707 }
708
709 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
710 VERIFY(result == vk::Result::eSuccess);
711}
712
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600713void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700714 // clean up staging resources
715 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600716 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
717 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700718}
719
720void Demo::draw() {
721 // Ensure no more than FRAME_LAG renderings are outstanding
722 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
723 device.resetFences(1, &fences[frame_index]);
724
725 vk::Result result;
726 do {
727 result =
728 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
729 if (result == vk::Result::eErrorOutOfDateKHR) {
730 // demo->swapchain is out of date (e.g. the window was resized) and
731 // must be recreated:
732 resize();
733 } else if (result == vk::Result::eSuboptimalKHR) {
734 // swapchain is not as optimal as it could be, but the platform's
735 // presentation engine will still present the image correctly.
736 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600737 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
738 inst.destroySurfaceKHR(surface, nullptr);
739 create_surface();
740 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700741 } else {
742 VERIFY(result == vk::Result::eSuccess);
743 }
744 } while (result != vk::Result::eSuccess);
745
746 update_data_buffer();
747
748 // Wait for the image acquired semaphore to be signaled to ensure
749 // that the image won't be rendered to until the presentation
750 // engine has fully released ownership to the application, and it is
751 // okay to render to the image.
752 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
753 auto const submit_info = vk::SubmitInfo()
754 .setPWaitDstStageMask(&pipe_stage_flags)
755 .setWaitSemaphoreCount(1)
756 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
757 .setCommandBufferCount(1)
758 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
759 .setSignalSemaphoreCount(1)
760 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
761
762 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
763 VERIFY(result == vk::Result::eSuccess);
764
765 if (separate_present_queue) {
766 // If we are using separate queues, change image ownership to the
767 // present queue before presenting, waiting for the draw complete
768 // semaphore and signalling the ownership released semaphore when
769 // finished
770 auto const present_submit_info = vk::SubmitInfo()
771 .setPWaitDstStageMask(&pipe_stage_flags)
772 .setWaitSemaphoreCount(1)
773 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
774 .setCommandBufferCount(1)
775 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
776 .setSignalSemaphoreCount(1)
777 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
778
779 result = present_queue.submit(1, &present_submit_info, vk::Fence());
780 VERIFY(result == vk::Result::eSuccess);
781 }
782
783 // If we are using separate queues we have to wait for image ownership,
784 // otherwise wait for draw complete
785 auto const presentInfo = vk::PresentInfoKHR()
786 .setWaitSemaphoreCount(1)
787 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
788 : &draw_complete_semaphores[frame_index])
789 .setSwapchainCount(1)
790 .setPSwapchains(&swapchain)
791 .setPImageIndices(&current_buffer);
792
793 result = present_queue.presentKHR(&presentInfo);
794 frame_index += 1;
795 frame_index %= FRAME_LAG;
796 if (result == vk::Result::eErrorOutOfDateKHR) {
797 // swapchain is out of date (e.g. the window was resized) and
798 // must be recreated:
799 resize();
800 } else if (result == vk::Result::eSuboptimalKHR) {
801 // swapchain is not as optimal as it could be, but the platform's
802 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600803 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
804 inst.destroySurfaceKHR(surface, nullptr);
805 create_surface();
806 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700807 } else {
808 VERIFY(result == vk::Result::eSuccess);
809 }
810}
811
812void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
813 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
814
815 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
816 vk::ClearDepthStencilValue(1.0f, 0u)};
817
818 auto const passInfo = vk::RenderPassBeginInfo()
819 .setRenderPass(render_pass)
820 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
821 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
822 .setClearValueCount(2)
823 .setPClearValues(clearValues);
824
825 auto result = commandBuffer.begin(&commandInfo);
826 VERIFY(result == vk::Result::eSuccess);
827
828 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
829 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
830 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
831 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700832 float viewport_dimension;
833 float viewport_x = 0.0f;
834 float viewport_y = 0.0f;
835 if (width < height) {
836 viewport_dimension = (float)width;
837 viewport_y = (height - width) / 2.0f;
838 } else {
839 viewport_dimension = (float)height;
840 viewport_x = (width - height) / 2.0f;
841 }
842 auto const viewport = vk::Viewport()
843 .setX(viewport_x)
844 .setY(viewport_y)
845 .setWidth((float)viewport_dimension)
846 .setHeight((float)viewport_dimension)
847 .setMinDepth((float)0.0f)
848 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700849 commandBuffer.setViewport(0, 1, &viewport);
850
851 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
852 commandBuffer.setScissor(0, 1, &scissor);
853 commandBuffer.draw(12 * 3, 1, 0, 0);
854 // Note that ending the renderpass changes the image's layout from
855 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
856 commandBuffer.endRenderPass();
857
858 if (separate_present_queue) {
859 // We have to transfer ownership from the graphics queue family to
860 // the
861 // present queue family to be able to present. Note that we don't
862 // have
863 // to transfer from present queue family back to graphics queue
864 // family at
865 // the start of the next frame because we don't care about the
866 // image's
867 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600868 auto const image_ownership_barrier =
869 vk::ImageMemoryBarrier()
870 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600871 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600872 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
873 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
874 .setSrcQueueFamilyIndex(graphics_queue_family_index)
875 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700876 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700877 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600878
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600879 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700880 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600881 }
882
Dave Houlton5fa47912018-02-16 11:02:26 -0700883 result = commandBuffer.end();
884 VERIFY(result == vk::Result::eSuccess);
885}
886
887void Demo::flush_init_cmd() {
888 // TODO: hmm.
889 // This function could get called twice if the texture uses a staging
890 // buffer
891 // In that case the second call should be ignored
892 if (!cmd) {
893 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600894 }
895
Dave Houlton5fa47912018-02-16 11:02:26 -0700896 auto result = cmd.end();
897 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600898
Dave Houlton5fa47912018-02-16 11:02:26 -0700899 auto const fenceInfo = vk::FenceCreateInfo();
900 vk::Fence fence;
901 result = device.createFence(&fenceInfo, nullptr, &fence);
902 VERIFY(result == vk::Result::eSuccess);
903
904 vk::CommandBuffer const commandBuffers[] = {cmd};
905 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
906
907 result = graphics_queue.submit(1, &submitInfo, fence);
908 VERIFY(result == vk::Result::eSuccess);
909
910 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
911 VERIFY(result == vk::Result::eSuccess);
912
913 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
914 device.destroyFence(fence, nullptr);
915
916 cmd = vk::CommandBuffer();
917}
918
919void Demo::init(int argc, char **argv) {
920 vec3 eye = {0.0f, 3.0f, 5.0f};
921 vec3 origin = {0, 0, 0};
922 vec3 up = {0.0f, 1.0f, 0.0};
923
924 presentMode = vk::PresentModeKHR::eFifo;
925 frameCount = UINT32_MAX;
926 use_xlib = false;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600927
Dave Houlton5fa47912018-02-16 11:02:26 -0700928 for (int i = 1; i < argc; i++) {
929 if (strcmp(argv[i], "--use_staging") == 0) {
930 use_staging_buffer = true;
931 continue;
932 }
933 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
934 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
935 i++;
936 continue;
937 }
938 if (strcmp(argv[i], "--break") == 0) {
939 use_break = true;
940 continue;
941 }
942 if (strcmp(argv[i], "--validate") == 0) {
943 validate = true;
944 continue;
945 }
946 if (strcmp(argv[i], "--xlib") == 0) {
947 fprintf(stderr, "--xlib is deprecated and no longer does anything");
948 continue;
949 }
950 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
951 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
952 i++;
953 continue;
954 }
955 if (strcmp(argv[i], "--suppress_popups") == 0) {
956 suppress_popups = true;
957 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600958 }
959
Tony-LunarGd74734f2019-06-04 14:11:43 -0600960 std::stringstream usage;
961 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
962 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
963 << "\t[--present_mode <present mode enum>]\n"
964 << "\t<present_mode_enum>\n"
965 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
966 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
967 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
968 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
969
970#if defined(_WIN32)
971 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
972#else
973 std::cerr << usage.str();
974 std::cerr.flush();
975#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700976 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600977 }
978
Dave Houlton5fa47912018-02-16 11:02:26 -0700979 if (!use_xlib) {
980 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600981 }
982
Dave Houlton5fa47912018-02-16 11:02:26 -0700983 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600984
Dave Houlton5fa47912018-02-16 11:02:26 -0700985 width = 500;
986 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600987
Dave Houlton5fa47912018-02-16 11:02:26 -0700988 spin_angle = 4.0f;
989 spin_increment = 0.2f;
990 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600991
Dave Houlton5fa47912018-02-16 11:02:26 -0700992 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
993 mat4x4_look_at(view_matrix, eye, origin, up);
994 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600995
Dave Houlton5fa47912018-02-16 11:02:26 -0700996 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
997}
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600998
Dave Houlton5fa47912018-02-16 11:02:26 -0700999void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001000#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001001 const xcb_setup_t *setup;
1002 xcb_screen_iterator_t iter;
1003 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001004
Dave Houlton5fa47912018-02-16 11:02:26 -07001005 const char *display_envar = getenv("DISPLAY");
1006 if (display_envar == nullptr || display_envar[0] == '\0') {
1007 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1008 fflush(stdout);
1009 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001010 }
1011
Dave Houlton5fa47912018-02-16 11:02:26 -07001012 connection = xcb_connect(nullptr, &scr);
1013 if (xcb_connection_has_error(connection) > 0) {
1014 printf(
1015 "Cannot find a compatible Vulkan installable client driver "
1016 "(ICD).\nExiting ...\n");
1017 fflush(stdout);
1018 exit(1);
1019 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001020
Dave Houlton5fa47912018-02-16 11:02:26 -07001021 setup = xcb_get_setup(connection);
1022 iter = xcb_setup_roots_iterator(setup);
1023 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001024
Dave Houlton5fa47912018-02-16 11:02:26 -07001025 screen = iter.data;
1026#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1027 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001028
Dave Houlton5fa47912018-02-16 11:02:26 -07001029 if (display == nullptr) {
1030 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1031 fflush(stdout);
1032 exit(1);
1033 }
1034
1035 registry = wl_display_get_registry(display);
1036 wl_registry_add_listener(registry, &registry_listener, this);
1037 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001038#endif
1039}
1040
1041void Demo::init_vk() {
1042 uint32_t instance_extension_count = 0;
1043 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001044 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001045 enabled_extension_count = 0;
1046 enabled_layer_count = 0;
1047
Dave Houlton5fa47912018-02-16 11:02:26 -07001048 // Look for validation layers
1049 vk::Bool32 validation_found = VK_FALSE;
1050 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001051 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001052 VERIFY(result == vk::Result::eSuccess);
1053
Dave Houlton5fa47912018-02-16 11:02:26 -07001054 if (instance_layer_count > 0) {
1055 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1056 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001057 VERIFY(result == vk::Result::eSuccess);
1058
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001059 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001060 instance_layer_count, instance_layers.get());
1061 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001062 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1063 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001064 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001065 }
1066
Dave Houlton5fa47912018-02-16 11:02:26 -07001067 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001068 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001069 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1070 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001071 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001072 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001073 }
1074
Dave Houlton5fa47912018-02-16 11:02:26 -07001075 /* Look for instance extensions */
1076 vk::Bool32 surfaceExtFound = VK_FALSE;
1077 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1078 memset(extension_names, 0, sizeof(extension_names));
1079
Mike Schuchardt7510c832018-10-29 13:23:08 -07001080 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1081 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001082 VERIFY(result == vk::Result::eSuccess);
1083
1084 if (instance_extension_count > 0) {
1085 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1086 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1087 VERIFY(result == vk::Result::eSuccess);
1088
1089 for (uint32_t i = 0; i < instance_extension_count; i++) {
1090 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1091 surfaceExtFound = 1;
1092 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1093 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001094#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001095 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1096 platformSurfaceExtFound = 1;
1097 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1098 }
1099#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1100 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1101 platformSurfaceExtFound = 1;
1102 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1103 }
1104#elif defined(VK_USE_PLATFORM_XCB_KHR)
1105 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1106 platformSurfaceExtFound = 1;
1107 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1108 }
Tony Barbour153cb062016-12-07 13:43:36 -07001109#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001110 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1111 platformSurfaceExtFound = 1;
1112 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1113 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001114#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1115 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1116 platformSurfaceExtFound = 1;
1117 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1118 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001119#elif defined(VK_USE_PLATFORM_METAL_EXT)
1120 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001121 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001122 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001123 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001124
Dave Houlton5fa47912018-02-16 11:02:26 -07001125#endif
1126 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001127 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001128 }
1129
1130 if (!surfaceExtFound) {
1131 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1132 " extension.\n\n"
1133 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1134 "Please look at the Getting Started guide for additional information.\n",
1135 "vkCreateInstance Failure");
1136 }
1137
1138 if (!platformSurfaceExtFound) {
1139#if defined(VK_USE_PLATFORM_WIN32_KHR)
1140 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1141 " extension.\n\n"
1142 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1143 "Please look at the Getting Started guide for additional information.\n",
1144 "vkCreateInstance Failure");
1145#elif defined(VK_USE_PLATFORM_XCB_KHR)
1146 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1147 " extension.\n\n"
1148 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1149 "Please look at the Getting Started guide for additional information.\n",
1150 "vkCreateInstance Failure");
1151#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1152 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1153 " extension.\n\n"
1154 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1155 "Please look at the Getting Started guide for additional information.\n",
1156 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001157#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001158 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1159 " extension.\n\n"
1160 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1161 "Please look at the Getting Started guide for additional information.\n",
1162 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001163#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001164 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1165 " extension.\n\n"
1166 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1167 "Please look at the Getting Started guide for additional information.\n",
1168 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001169#elif defined(VK_USE_PLATFORM_METAL_EXT)
1170 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001171 " extension.\n\nDo you have a compatible "
1172 "Vulkan installable client driver (ICD) installed?\nPlease "
1173 "look at the Getting Started guide for additional "
1174 "information.\n",
1175 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001176#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001177 }
1178 auto const app = vk::ApplicationInfo()
1179 .setPApplicationName(APP_SHORT_NAME)
1180 .setApplicationVersion(0)
1181 .setPEngineName(APP_SHORT_NAME)
1182 .setEngineVersion(0)
1183 .setApiVersion(VK_API_VERSION_1_0);
1184 auto const inst_info = vk::InstanceCreateInfo()
1185 .setPApplicationInfo(&app)
1186 .setEnabledLayerCount(enabled_layer_count)
1187 .setPpEnabledLayerNames(instance_validation_layers)
1188 .setEnabledExtensionCount(enabled_extension_count)
1189 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001190
Dave Houlton5fa47912018-02-16 11:02:26 -07001191 result = vk::createInstance(&inst_info, nullptr, &inst);
1192 if (result == vk::Result::eErrorIncompatibleDriver) {
1193 ERR_EXIT(
1194 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1195 "Please look at the Getting Started guide for additional information.\n",
1196 "vkCreateInstance Failure");
1197 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1198 ERR_EXIT(
1199 "Cannot find a specified extension library.\n"
1200 "Make sure your layers path is set appropriately.\n",
1201 "vkCreateInstance Failure");
1202 } else if (result != vk::Result::eSuccess) {
1203 ERR_EXIT(
1204 "vkCreateInstance failed.\n\n"
1205 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1206 "Please look at the Getting Started guide for additional information.\n",
1207 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001208 }
1209
Dave Houlton5fa47912018-02-16 11:02:26 -07001210 /* Make initial call to query gpu_count, then second call for gpu info*/
1211 uint32_t gpu_count;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001212 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001213 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001214
1215 if (gpu_count > 0) {
1216 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1217 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001218 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001219 /* For cube demo we just grab the first physical device */
1220 gpu = physical_devices[0];
1221 } else {
1222 ERR_EXIT(
1223 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1224 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1225 "Please look at the Getting Started guide for additional information.\n",
1226 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001227 }
1228
Dave Houlton5fa47912018-02-16 11:02:26 -07001229 /* Look for device extensions */
1230 uint32_t device_extension_count = 0;
1231 vk::Bool32 swapchainExtFound = VK_FALSE;
1232 enabled_extension_count = 0;
1233 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001234
Mike Schuchardt7510c832018-10-29 13:23:08 -07001235 result =
1236 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001237 VERIFY(result == vk::Result::eSuccess);
1238
1239 if (device_extension_count > 0) {
1240 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1241 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001242 VERIFY(result == vk::Result::eSuccess);
1243
Dave Houlton5fa47912018-02-16 11:02:26 -07001244 for (uint32_t i = 0; i < device_extension_count; i++) {
1245 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1246 swapchainExtFound = 1;
1247 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001248 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001249 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001250 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001251 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001252
Dave Houlton5fa47912018-02-16 11:02:26 -07001253 if (!swapchainExtFound) {
1254 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1255 " extension.\n\n"
1256 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1257 "Please look at the Getting Started guide for additional information.\n",
1258 "vkCreateInstance Failure");
1259 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001260
Dave Houlton5fa47912018-02-16 11:02:26 -07001261 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001262
Dave Houlton5fa47912018-02-16 11:02:26 -07001263 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001264 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001265 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001266
Dave Houlton5fa47912018-02-16 11:02:26 -07001267 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1268 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001269
Dave Houlton5fa47912018-02-16 11:02:26 -07001270 // Query fine-grained feature support for this device.
1271 // If app has specific feature requirements it should check supported
1272 // features based on this query
1273 vk::PhysicalDeviceFeatures physDevFeatures;
1274 gpu.getFeatures(&physDevFeatures);
1275}
1276
Tony-LunarG6cebf142019-09-11 14:32:23 -06001277void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001278// Create a WSI surface for the window:
1279#if defined(VK_USE_PLATFORM_WIN32_KHR)
1280 {
1281 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1282
1283 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1284 VERIFY(result == vk::Result::eSuccess);
1285 }
1286#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1287 {
1288 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1289
1290 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1291 VERIFY(result == vk::Result::eSuccess);
1292 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001293#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1294 {
1295 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1296
1297 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1298 VERIFY(result == vk::Result::eSuccess);
1299 }
1300#elif defined(VK_USE_PLATFORM_XCB_KHR)
1301 {
1302 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1303
1304 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1305 VERIFY(result == vk::Result::eSuccess);
1306 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001307#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001308 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001309 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001310
Bill Hollings0a0625a2019-07-15 17:39:18 -04001311 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001312 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
Tony-LunarG6cebf142019-09-11 14:32:23 -06001320}
1321
1322void Demo::init_vk_swapchain() {
1323 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001324 // Iterate over each queue to learn whether it supports presenting:
1325 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1326 for (uint32_t i = 0; i < queue_family_count; i++) {
1327 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1328 }
1329
1330 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1331 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1332 for (uint32_t i = 0; i < queue_family_count; i++) {
1333 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1334 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1335 graphicsQueueFamilyIndex = i;
1336 }
1337
1338 if (supportsPresent[i] == VK_TRUE) {
1339 graphicsQueueFamilyIndex = i;
1340 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001341 break;
1342 }
1343 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001344 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001345
Dave Houlton5fa47912018-02-16 11:02:26 -07001346 if (presentQueueFamilyIndex == UINT32_MAX) {
1347 // If didn't find a queue that supports both graphics and present,
1348 // then
1349 // find a separate present queue.
1350 for (uint32_t i = 0; i < queue_family_count; ++i) {
1351 if (supportsPresent[i] == VK_TRUE) {
1352 presentQueueFamilyIndex = i;
1353 break;
1354 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001355 }
1356 }
1357
Dave Houlton5fa47912018-02-16 11:02:26 -07001358 // Generate error if could not find both a graphics and a present queue
1359 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1360 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1361 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001362
Dave Houlton5fa47912018-02-16 11:02:26 -07001363 graphics_queue_family_index = graphicsQueueFamilyIndex;
1364 present_queue_family_index = presentQueueFamilyIndex;
1365 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001366
Dave Houlton5fa47912018-02-16 11:02:26 -07001367 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001368
Dave Houlton5fa47912018-02-16 11:02:26 -07001369 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1370 if (!separate_present_queue) {
1371 present_queue = graphics_queue;
1372 } else {
1373 device.getQueue(present_queue_family_index, 0, &present_queue);
1374 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001375
Dave Houlton5fa47912018-02-16 11:02:26 -07001376 // Get the list of VkFormat's that are supported:
1377 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001378 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001379 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001380
Dave Houlton5fa47912018-02-16 11:02:26 -07001381 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1382 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1383 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001384
Dave Houlton5fa47912018-02-16 11:02:26 -07001385 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1386 // the surface has no preferred format. Otherwise, at least one
1387 // supported format will be returned.
1388 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1389 format = vk::Format::eB8G8R8A8Unorm;
1390 } else {
1391 assert(formatCount >= 1);
1392 format = surfFormats[0].format;
1393 }
1394 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001395
Dave Houlton5fa47912018-02-16 11:02:26 -07001396 quit = false;
1397 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001398
Dave Houlton5fa47912018-02-16 11:02:26 -07001399 // Create semaphores to synchronize acquiring presentable buffers before
1400 // rendering and waiting for drawing to be complete before presenting
1401 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001402
Dave Houlton5fa47912018-02-16 11:02:26 -07001403 // Create fences that we can use to throttle if we get too far
1404 // ahead of the image presents
1405 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1406 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1407 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1408 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001409
Dave Houlton5fa47912018-02-16 11:02:26 -07001410 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1411 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001412
Dave Houlton5fa47912018-02-16 11:02:26 -07001413 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1414 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001415
Dave Houlton5fa47912018-02-16 11:02:26 -07001416 if (separate_present_queue) {
1417 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001418 VERIFY(result == vk::Result::eSuccess);
1419 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001420 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001421 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001422
Dave Houlton5fa47912018-02-16 11:02:26 -07001423 // Get Memory information and properties
1424 gpu.getMemoryProperties(&memory_properties);
1425}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001426
Dave Houlton5fa47912018-02-16 11:02:26 -07001427void Demo::prepare() {
1428 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1429 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1430 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001431
Dave Houlton5fa47912018-02-16 11:02:26 -07001432 auto const cmd = vk::CommandBufferAllocateInfo()
1433 .setCommandPool(cmd_pool)
1434 .setLevel(vk::CommandBufferLevel::ePrimary)
1435 .setCommandBufferCount(1);
1436
1437 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1438 VERIFY(result == vk::Result::eSuccess);
1439
1440 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1441
1442 result = this->cmd.begin(&cmd_buf_info);
1443 VERIFY(result == vk::Result::eSuccess);
1444
1445 prepare_buffers();
1446 prepare_depth();
1447 prepare_textures();
1448 prepare_cube_data_buffers();
1449
1450 prepare_descriptor_layout();
1451 prepare_render_pass();
1452 prepare_pipeline();
1453
1454 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1455 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1456 VERIFY(result == vk::Result::eSuccess);
1457 }
1458
1459 if (separate_present_queue) {
1460 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1461
1462 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1463 VERIFY(result == vk::Result::eSuccess);
1464
1465 auto const present_cmd = vk::CommandBufferAllocateInfo()
1466 .setCommandPool(present_cmd_pool)
1467 .setLevel(vk::CommandBufferLevel::ePrimary)
1468 .setCommandBufferCount(1);
1469
1470 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1471 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1472 VERIFY(result == vk::Result::eSuccess);
1473
1474 build_image_ownership_cmd(i);
1475 }
1476 }
1477
1478 prepare_descriptor_pool();
1479 prepare_descriptor_set();
1480
1481 prepare_framebuffers();
1482
1483 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1484 current_buffer = i;
1485 draw_build_cmd(swapchain_image_resources[i].cmd);
1486 }
1487
1488 /*
1489 * Prepare functions above may generate pipeline commands
1490 * that need to be flushed before beginning the render loop.
1491 */
1492 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001493 if (staging_texture.buffer) {
1494 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001495 }
1496
1497 current_buffer = 0;
1498 prepared = true;
1499}
1500
1501void Demo::prepare_buffers() {
1502 vk::SwapchainKHR oldSwapchain = swapchain;
1503
1504 // Check the surface capabilities and formats
1505 vk::SurfaceCapabilitiesKHR surfCapabilities;
1506 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1507 VERIFY(result == vk::Result::eSuccess);
1508
1509 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001510 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001511 VERIFY(result == vk::Result::eSuccess);
1512
1513 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1514 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1515 VERIFY(result == vk::Result::eSuccess);
1516
1517 vk::Extent2D swapchainExtent;
1518 // width and height are either both -1, or both not -1.
1519 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1520 // If the surface size is undefined, the size is set to
1521 // the size of the images requested.
1522 swapchainExtent.width = width;
1523 swapchainExtent.height = height;
1524 } else {
1525 // If the surface size is defined, the swap chain size must match
1526 swapchainExtent = surfCapabilities.currentExtent;
1527 width = surfCapabilities.currentExtent.width;
1528 height = surfCapabilities.currentExtent.height;
1529 }
1530
1531 // The FIFO present mode is guaranteed by the spec to be supported
1532 // and to have no tearing. It's a great default present mode to use.
1533 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1534
1535 // There are times when you may wish to use another present mode. The
1536 // following code shows how to select them, and the comments provide some
1537 // reasons you may wish to use them.
1538 //
1539 // It should be noted that Vulkan 1.0 doesn't provide a method for
1540 // synchronizing rendering with the presentation engine's display. There
1541 // is a method provided for throttling rendering with the display, but
1542 // there are some presentation engines for which this method will not work.
1543 // If an application doesn't throttle its rendering, and if it renders much
1544 // faster than the refresh rate of the display, this can waste power on
1545 // mobile devices. That is because power is being spent rendering images
1546 // that may never be seen.
1547
1548 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1549 // about
1550 // tearing, or have some way of synchronizing their rendering with the
1551 // display.
1552 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1553 // generally render a new presentable image every refresh cycle, but are
1554 // occasionally early. In this case, the application wants the new
1555 // image
1556 // to be displayed instead of the previously-queued-for-presentation
1557 // image
1558 // that has not yet been displayed.
1559 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1560 // render a new presentable image every refresh cycle, but are
1561 // occasionally
1562 // late. In this case (perhaps because of stuttering/latency concerns),
1563 // the application wants the late image to be immediately displayed,
1564 // even
1565 // though that may mean some tearing.
1566
1567 if (presentMode != swapchainPresentMode) {
1568 for (size_t i = 0; i < presentModeCount; ++i) {
1569 if (presentModes[i] == presentMode) {
1570 swapchainPresentMode = presentMode;
1571 break;
1572 }
1573 }
1574 }
1575
1576 if (swapchainPresentMode != presentMode) {
1577 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1578 }
1579
1580 // Determine the number of VkImages to use in the swap chain.
1581 // Application desires to acquire 3 images at a time for triple
1582 // buffering
1583 uint32_t desiredNumOfSwapchainImages = 3;
1584 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1585 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1586 }
1587
1588 // If maxImageCount is 0, we can ask for as many images as we want,
1589 // otherwise
1590 // we're limited to maxImageCount
1591 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1592 // Application must settle for fewer images than desired:
1593 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1594 }
1595
1596 vk::SurfaceTransformFlagBitsKHR preTransform;
1597 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1598 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1599 } else {
1600 preTransform = surfCapabilities.currentTransform;
1601 }
1602
1603 // Find a supported composite alpha mode - one of these is guaranteed to be set
1604 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1605 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1606 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1607 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1608 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1609 vk::CompositeAlphaFlagBitsKHR::eInherit,
1610 };
1611 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1612 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1613 compositeAlpha = compositeAlphaFlags[i];
1614 break;
1615 }
1616 }
1617
1618 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1619 .setSurface(surface)
1620 .setMinImageCount(desiredNumOfSwapchainImages)
1621 .setImageFormat(format)
1622 .setImageColorSpace(color_space)
1623 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1624 .setImageArrayLayers(1)
1625 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1626 .setImageSharingMode(vk::SharingMode::eExclusive)
1627 .setQueueFamilyIndexCount(0)
1628 .setPQueueFamilyIndices(nullptr)
1629 .setPreTransform(preTransform)
1630 .setCompositeAlpha(compositeAlpha)
1631 .setPresentMode(swapchainPresentMode)
1632 .setClipped(true)
1633 .setOldSwapchain(oldSwapchain);
1634
1635 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1636 VERIFY(result == vk::Result::eSuccess);
1637
1638 // If we just re-created an existing swapchain, we should destroy the
1639 // old
1640 // swapchain at this point.
1641 // Note: destroying the swapchain also cleans up all its associated
1642 // presentable images once the platform is done with them.
1643 if (oldSwapchain) {
1644 device.destroySwapchainKHR(oldSwapchain, nullptr);
1645 }
1646
Mike Schuchardt7510c832018-10-29 13:23:08 -07001647 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001648 VERIFY(result == vk::Result::eSuccess);
1649
1650 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1651 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1652 VERIFY(result == vk::Result::eSuccess);
1653
1654 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1655
1656 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1657 auto color_image_view = vk::ImageViewCreateInfo()
1658 .setViewType(vk::ImageViewType::e2D)
1659 .setFormat(format)
1660 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1661
1662 swapchain_image_resources[i].image = swapchainImages[i];
1663
1664 color_image_view.image = swapchain_image_resources[i].image;
1665
1666 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1667 VERIFY(result == vk::Result::eSuccess);
1668 }
1669}
1670
1671void Demo::prepare_cube_data_buffers() {
1672 mat4x4 VP;
1673 mat4x4_mul(VP, projection_matrix, view_matrix);
1674
1675 mat4x4 MVP;
1676 mat4x4_mul(MVP, VP, model_matrix);
1677
1678 vktexcube_vs_uniform data;
1679 memcpy(data.mvp, MVP, sizeof(MVP));
1680 // dumpMatrix("MVP", MVP)
1681
1682 for (int32_t i = 0; i < 12 * 3; i++) {
1683 data.position[i][0] = g_vertex_buffer_data[i * 3];
1684 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1685 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1686 data.position[i][3] = 1.0f;
1687 data.attr[i][0] = g_uv_buffer_data[2 * i];
1688 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1689 data.attr[i][2] = 0;
1690 data.attr[i][3] = 0;
1691 }
1692
1693 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1694
1695 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1696 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001697 VERIFY(result == vk::Result::eSuccess);
1698
1699 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001700 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001701
Dave Houlton5fa47912018-02-16 11:02:26 -07001702 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001703
Dave Houlton5fa47912018-02-16 11:02:26 -07001704 bool const pass = memory_type_from_properties(
1705 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1706 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001707 VERIFY(pass);
1708
Dave Houlton5fa47912018-02-16 11:02:26 -07001709 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001710 VERIFY(result == vk::Result::eSuccess);
1711
Tony-LunarG37af49f2019-12-19 12:04:19 -07001712 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1713 &swapchain_image_resources[i].uniform_memory_ptr);
1714 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001715
Tony-LunarG37af49f2019-12-19 12:04:19 -07001716 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001717
1718 result =
1719 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001720 VERIFY(result == vk::Result::eSuccess);
1721 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001722}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001723
Dave Houlton5fa47912018-02-16 11:02:26 -07001724void Demo::prepare_depth() {
1725 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001726
Dave Houlton5fa47912018-02-16 11:02:26 -07001727 auto const image = vk::ImageCreateInfo()
1728 .setImageType(vk::ImageType::e2D)
1729 .setFormat(depth.format)
1730 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1731 .setMipLevels(1)
1732 .setArrayLayers(1)
1733 .setSamples(vk::SampleCountFlagBits::e1)
1734 .setTiling(vk::ImageTiling::eOptimal)
1735 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1736 .setSharingMode(vk::SharingMode::eExclusive)
1737 .setQueueFamilyIndexCount(0)
1738 .setPQueueFamilyIndices(nullptr)
1739 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001740
Dave Houlton5fa47912018-02-16 11:02:26 -07001741 auto result = device.createImage(&image, nullptr, &depth.image);
1742 VERIFY(result == vk::Result::eSuccess);
1743
1744 vk::MemoryRequirements mem_reqs;
1745 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1746
1747 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1748 depth.mem_alloc.setMemoryTypeIndex(0);
1749
1750 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1751 &depth.mem_alloc.memoryTypeIndex);
1752 VERIFY(pass);
1753
1754 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1755 VERIFY(result == vk::Result::eSuccess);
1756
1757 result = device.bindImageMemory(depth.image, depth.mem, 0);
1758 VERIFY(result == vk::Result::eSuccess);
1759
1760 auto const view = vk::ImageViewCreateInfo()
1761 .setImage(depth.image)
1762 .setViewType(vk::ImageViewType::e2D)
1763 .setFormat(depth.format)
1764 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1765 result = device.createImageView(&view, nullptr, &depth.view);
1766 VERIFY(result == vk::Result::eSuccess);
1767}
1768
1769void Demo::prepare_descriptor_layout() {
1770 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1771 .setBinding(0)
1772 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1773 .setDescriptorCount(1)
1774 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1775 .setPImmutableSamplers(nullptr),
1776 vk::DescriptorSetLayoutBinding()
1777 .setBinding(1)
1778 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1779 .setDescriptorCount(texture_count)
1780 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1781 .setPImmutableSamplers(nullptr)};
1782
1783 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1784
1785 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1786 VERIFY(result == vk::Result::eSuccess);
1787
1788 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1789
1790 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1791 VERIFY(result == vk::Result::eSuccess);
1792}
1793
1794void Demo::prepare_descriptor_pool() {
1795 vk::DescriptorPoolSize const poolSizes[2] = {
1796 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1797 vk::DescriptorPoolSize()
1798 .setType(vk::DescriptorType::eCombinedImageSampler)
1799 .setDescriptorCount(swapchainImageCount * texture_count)};
1800
1801 auto const descriptor_pool =
1802 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1803
1804 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1805 VERIFY(result == vk::Result::eSuccess);
1806}
1807
1808void Demo::prepare_descriptor_set() {
1809 auto const alloc_info =
1810 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1811
1812 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1813
1814 vk::DescriptorImageInfo tex_descs[texture_count];
1815 for (uint32_t i = 0; i < texture_count; i++) {
1816 tex_descs[i].setSampler(textures[i].sampler);
1817 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001818 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001819 }
1820
1821 vk::WriteDescriptorSet writes[2];
1822
1823 writes[0].setDescriptorCount(1);
1824 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1825 writes[0].setPBufferInfo(&buffer_info);
1826
1827 writes[1].setDstBinding(1);
1828 writes[1].setDescriptorCount(texture_count);
1829 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1830 writes[1].setPImageInfo(tex_descs);
1831
1832 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1833 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001834 VERIFY(result == vk::Result::eSuccess);
1835
Dave Houlton5fa47912018-02-16 11:02:26 -07001836 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1837 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1838 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1839 device.updateDescriptorSets(2, writes, 0, nullptr);
1840 }
1841}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001842
Dave Houlton5fa47912018-02-16 11:02:26 -07001843void Demo::prepare_framebuffers() {
1844 vk::ImageView attachments[2];
1845 attachments[1] = depth.view;
1846
1847 auto const fb_info = vk::FramebufferCreateInfo()
1848 .setRenderPass(render_pass)
1849 .setAttachmentCount(2)
1850 .setPAttachments(attachments)
1851 .setWidth((uint32_t)width)
1852 .setHeight((uint32_t)height)
1853 .setLayers(1);
1854
1855 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1856 attachments[0] = swapchain_image_resources[i].view;
1857 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001858 VERIFY(result == vk::Result::eSuccess);
1859 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001860}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001861
Dave Houlton5fa47912018-02-16 11:02:26 -07001862vk::ShaderModule Demo::prepare_fs() {
1863 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001864#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001865 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001866
Dave Houlton5fa47912018-02-16 11:02:26 -07001867 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001868
Dave Houlton5fa47912018-02-16 11:02:26 -07001869 return frag_shader_module;
1870}
1871
1872void Demo::prepare_pipeline() {
1873 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1874 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1875 VERIFY(result == vk::Result::eSuccess);
1876
1877 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1878 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1879 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1880
1881 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1882
1883 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1884
1885 // TODO: Where are pViewports and pScissors set?
1886 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1887
1888 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1889 .setDepthClampEnable(VK_FALSE)
1890 .setRasterizerDiscardEnable(VK_FALSE)
1891 .setPolygonMode(vk::PolygonMode::eFill)
1892 .setCullMode(vk::CullModeFlagBits::eBack)
1893 .setFrontFace(vk::FrontFace::eCounterClockwise)
1894 .setDepthBiasEnable(VK_FALSE)
1895 .setLineWidth(1.0f);
1896
1897 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1898
1899 auto const stencilOp =
1900 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1901
1902 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1903 .setDepthTestEnable(VK_TRUE)
1904 .setDepthWriteEnable(VK_TRUE)
1905 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1906 .setDepthBoundsTestEnable(VK_FALSE)
1907 .setStencilTestEnable(VK_FALSE)
1908 .setFront(stencilOp)
1909 .setBack(stencilOp);
1910
1911 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1912 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1913 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1914
1915 auto const colorBlendInfo =
1916 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1917
1918 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1919
1920 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1921
1922 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1923 .setStageCount(2)
1924 .setPStages(shaderStageInfo)
1925 .setPVertexInputState(&vertexInputInfo)
1926 .setPInputAssemblyState(&inputAssemblyInfo)
1927 .setPViewportState(&viewportInfo)
1928 .setPRasterizationState(&rasterizationInfo)
1929 .setPMultisampleState(&multisampleInfo)
1930 .setPDepthStencilState(&depthStencilInfo)
1931 .setPColorBlendState(&colorBlendInfo)
1932 .setPDynamicState(&dynamicStateInfo)
1933 .setLayout(pipeline_layout)
1934 .setRenderPass(render_pass);
1935
1936 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1937 VERIFY(result == vk::Result::eSuccess);
1938
1939 device.destroyShaderModule(frag_shader_module, nullptr);
1940 device.destroyShaderModule(vert_shader_module, nullptr);
1941}
1942
1943void Demo::prepare_render_pass() {
1944 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1945 // because at the start of the renderpass, we don't care about their contents.
1946 // At the start of the subpass, the color attachment's layout will be transitioned
1947 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1948 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1949 // the renderpass, the color attachment's layout will be transitioned to
1950 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1951 // the renderpass, no barriers are necessary.
1952 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1953 .setFormat(format)
1954 .setSamples(vk::SampleCountFlagBits::e1)
1955 .setLoadOp(vk::AttachmentLoadOp::eClear)
1956 .setStoreOp(vk::AttachmentStoreOp::eStore)
1957 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1958 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1959 .setInitialLayout(vk::ImageLayout::eUndefined)
1960 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1961 vk::AttachmentDescription()
1962 .setFormat(depth.format)
1963 .setSamples(vk::SampleCountFlagBits::e1)
1964 .setLoadOp(vk::AttachmentLoadOp::eClear)
1965 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1966 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1967 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1968 .setInitialLayout(vk::ImageLayout::eUndefined)
1969 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1970
1971 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1972
1973 auto const depth_reference =
1974 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1975
1976 auto const subpass = vk::SubpassDescription()
1977 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1978 .setInputAttachmentCount(0)
1979 .setPInputAttachments(nullptr)
1980 .setColorAttachmentCount(1)
1981 .setPColorAttachments(&color_reference)
1982 .setPResolveAttachments(nullptr)
1983 .setPDepthStencilAttachment(&depth_reference)
1984 .setPreserveAttachmentCount(0)
1985 .setPPreserveAttachments(nullptr);
1986
Tony-LunarG495604b2019-06-13 15:32:05 -06001987 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
1988 vk::SubpassDependency const dependencies[2] = {
1989 vk::SubpassDependency() // Depth buffer is shared between swapchain images
1990 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
1991 .setDstSubpass(0)
1992 .setSrcStageMask(stages)
1993 .setDstStageMask(stages)
1994 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
1995 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
1996 .setDependencyFlags(vk::DependencyFlags()),
1997 vk::SubpassDependency() // Image layout transition
1998 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
1999 .setDstSubpass(0)
2000 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2001 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2002 .setSrcAccessMask(vk::AccessFlagBits())
2003 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2004 .setDependencyFlags(vk::DependencyFlags()),
2005 };
2006
Dave Houlton5fa47912018-02-16 11:02:26 -07002007 auto const rp_info = vk::RenderPassCreateInfo()
2008 .setAttachmentCount(2)
2009 .setPAttachments(attachments)
2010 .setSubpassCount(1)
2011 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002012 .setDependencyCount(2)
2013 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002014
2015 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2016 VERIFY(result == vk::Result::eSuccess);
2017}
2018
2019vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2020 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2021
2022 vk::ShaderModule module;
2023 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2024 VERIFY(result == vk::Result::eSuccess);
2025
2026 return module;
2027}
2028
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002029void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2030 int32_t tex_width;
2031 int32_t tex_height;
2032
2033 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2034 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2035 }
2036
2037 tex_obj->tex_width = tex_width;
2038 tex_obj->tex_height = tex_height;
2039
2040 auto const buffer_create_info = vk::BufferCreateInfo()
2041 .setSize(tex_width * tex_height * 4)
2042 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2043 .setSharingMode(vk::SharingMode::eExclusive)
2044 .setQueueFamilyIndexCount(0)
2045 .setPQueueFamilyIndices(nullptr);
2046
2047 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2048 VERIFY(result == vk::Result::eSuccess);
2049
2050 vk::MemoryRequirements mem_reqs;
2051 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2052
2053 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2054 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2055
2056 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2057 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2058 VERIFY(pass == true);
2059
2060 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2061 VERIFY(result == vk::Result::eSuccess);
2062
2063 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2064 VERIFY(result == vk::Result::eSuccess);
2065
2066 vk::SubresourceLayout layout;
2067 memset(&layout, 0, sizeof(layout));
2068 layout.rowPitch = tex_width * 4;
2069 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2070 VERIFY(data.result == vk::Result::eSuccess);
2071
2072 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2073 fprintf(stderr, "Error loading texture: %s\n", filename);
2074 }
2075
2076 device.unmapMemory(tex_obj->mem);
2077}
2078
Dave Houlton5fa47912018-02-16 11:02:26 -07002079void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2080 vk::MemoryPropertyFlags required_props) {
2081 int32_t tex_width;
2082 int32_t tex_height;
2083 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2084 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002085 }
2086
Dave Houlton5fa47912018-02-16 11:02:26 -07002087 tex_obj->tex_width = tex_width;
2088 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002089
Dave Houlton5fa47912018-02-16 11:02:26 -07002090 auto const image_create_info = vk::ImageCreateInfo()
2091 .setImageType(vk::ImageType::e2D)
2092 .setFormat(vk::Format::eR8G8B8A8Unorm)
2093 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2094 .setMipLevels(1)
2095 .setArrayLayers(1)
2096 .setSamples(vk::SampleCountFlagBits::e1)
2097 .setTiling(tiling)
2098 .setUsage(usage)
2099 .setSharingMode(vk::SharingMode::eExclusive)
2100 .setQueueFamilyIndexCount(0)
2101 .setPQueueFamilyIndices(nullptr)
2102 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002103
Dave Houlton5fa47912018-02-16 11:02:26 -07002104 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2105 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002106
Dave Houlton5fa47912018-02-16 11:02:26 -07002107 vk::MemoryRequirements mem_reqs;
2108 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002109
Dave Houlton5fa47912018-02-16 11:02:26 -07002110 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2111 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002112
Dave Houlton5fa47912018-02-16 11:02:26 -07002113 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2114 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002115
Dave Houlton5fa47912018-02-16 11:02:26 -07002116 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2117 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002118
Dave Houlton5fa47912018-02-16 11:02:26 -07002119 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2120 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002121
Dave Houlton5fa47912018-02-16 11:02:26 -07002122 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2123 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2124 vk::SubresourceLayout layout;
2125 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002126
Dave Houlton5fa47912018-02-16 11:02:26 -07002127 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002128 VERIFY(data.result == vk::Result::eSuccess);
2129
Dave Houlton5fa47912018-02-16 11:02:26 -07002130 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2131 fprintf(stderr, "Error loading texture: %s\n", filename);
2132 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002133
Dave Houlton5fa47912018-02-16 11:02:26 -07002134 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002135 }
2136
Dave Houlton5fa47912018-02-16 11:02:26 -07002137 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2138}
2139
2140void Demo::prepare_textures() {
2141 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2142 vk::FormatProperties props;
2143 gpu.getFormatProperties(tex_format, &props);
2144
2145 for (uint32_t i = 0; i < texture_count; i++) {
2146 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2147 /* Device can texture using linear textures */
2148 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2149 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2150 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2151 // shader to run until layout transition completes
2152 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2153 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2154 vk::PipelineStageFlagBits::eFragmentShader);
2155 staging_texture.image = vk::Image();
2156 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2157 /* Must use staging buffer to copy linear texture to optimized */
2158
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002159 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002160
2161 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2162 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2163 vk::MemoryPropertyFlagBits::eDeviceLocal);
2164
Dave Houlton5fa47912018-02-16 11:02:26 -07002165 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2166 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2167 vk::PipelineStageFlagBits::eTransfer);
2168
2169 auto const subresource = vk::ImageSubresourceLayers()
2170 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2171 .setMipLevel(0)
2172 .setBaseArrayLayer(0)
2173 .setLayerCount(1);
2174
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002175 auto const copy_region =
2176 vk::BufferImageCopy()
2177 .setBufferOffset(0)
2178 .setBufferRowLength(staging_texture.tex_width)
2179 .setBufferImageHeight(staging_texture.tex_height)
2180 .setImageSubresource(subresource)
2181 .setImageOffset({0, 0, 0})
2182 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002183
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002184 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002185
2186 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2187 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2188 vk::PipelineStageFlagBits::eFragmentShader);
2189 } else {
2190 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002191 }
2192
Dave Houlton5fa47912018-02-16 11:02:26 -07002193 auto const samplerInfo = vk::SamplerCreateInfo()
2194 .setMagFilter(vk::Filter::eNearest)
2195 .setMinFilter(vk::Filter::eNearest)
2196 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2197 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2198 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2199 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2200 .setMipLodBias(0.0f)
2201 .setAnisotropyEnable(VK_FALSE)
2202 .setMaxAnisotropy(1)
2203 .setCompareEnable(VK_FALSE)
2204 .setCompareOp(vk::CompareOp::eNever)
2205 .setMinLod(0.0f)
2206 .setMaxLod(0.0f)
2207 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2208 .setUnnormalizedCoordinates(VK_FALSE);
2209
2210 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2211 VERIFY(result == vk::Result::eSuccess);
2212
2213 auto const viewInfo = vk::ImageViewCreateInfo()
2214 .setImage(textures[i].image)
2215 .setViewType(vk::ImageViewType::e2D)
2216 .setFormat(tex_format)
2217 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2218
2219 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2220 VERIFY(result == vk::Result::eSuccess);
2221 }
2222}
2223
2224vk::ShaderModule Demo::prepare_vs() {
2225 const uint32_t vertShaderCode[] = {
2226#include "cube.vert.inc"
2227 };
2228
2229 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2230
2231 return vert_shader_module;
2232}
2233
2234void Demo::resize() {
2235 uint32_t i;
2236
2237 // Don't react to resize until after first initialization.
2238 if (!prepared) {
2239 return;
2240 }
2241
2242 // In order to properly resize the window, we must re-create the
2243 // swapchain
2244 // AND redo the command buffers, etc.
2245 //
2246 // First, perform part of the cleanup() function:
2247 prepared = false;
2248 auto result = device.waitIdle();
2249 VERIFY(result == vk::Result::eSuccess);
2250
2251 for (i = 0; i < swapchainImageCount; i++) {
2252 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2253 }
2254
2255 device.destroyDescriptorPool(desc_pool, nullptr);
2256
2257 device.destroyPipeline(pipeline, nullptr);
2258 device.destroyPipelineCache(pipelineCache, nullptr);
2259 device.destroyRenderPass(render_pass, nullptr);
2260 device.destroyPipelineLayout(pipeline_layout, nullptr);
2261 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2262
2263 for (i = 0; i < texture_count; i++) {
2264 device.destroyImageView(textures[i].view, nullptr);
2265 device.destroyImage(textures[i].image, nullptr);
2266 device.freeMemory(textures[i].mem, nullptr);
2267 device.destroySampler(textures[i].sampler, nullptr);
2268 }
2269
2270 device.destroyImageView(depth.view, nullptr);
2271 device.destroyImage(depth.image, nullptr);
2272 device.freeMemory(depth.mem, nullptr);
2273
2274 for (i = 0; i < swapchainImageCount; i++) {
2275 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2276 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2277 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002278 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002279 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2280 }
2281
2282 device.destroyCommandPool(cmd_pool, nullptr);
2283 if (separate_present_queue) {
2284 device.destroyCommandPool(present_cmd_pool, nullptr);
2285 }
2286
2287 // Second, re-perform the prepare() function, which will re-create the
2288 // swapchain.
2289 prepare();
2290}
2291
2292void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2293 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2294 assert(cmd);
2295
2296 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2297 vk::AccessFlags flags;
2298
2299 switch (layout) {
2300 case vk::ImageLayout::eTransferDstOptimal:
2301 // Make sure anything that was copying from this image has
2302 // completed
2303 flags = vk::AccessFlagBits::eTransferWrite;
2304 break;
2305 case vk::ImageLayout::eColorAttachmentOptimal:
2306 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2307 break;
2308 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2309 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2310 break;
2311 case vk::ImageLayout::eShaderReadOnlyOptimal:
2312 // Make sure any Copy or CPU writes to image are flushed
2313 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2314 break;
2315 case vk::ImageLayout::eTransferSrcOptimal:
2316 flags = vk::AccessFlagBits::eTransferRead;
2317 break;
2318 case vk::ImageLayout::ePresentSrcKHR:
2319 flags = vk::AccessFlagBits::eMemoryRead;
2320 break;
2321 default:
2322 break;
2323 }
2324
2325 return flags;
2326 };
2327
2328 auto const barrier = vk::ImageMemoryBarrier()
2329 .setSrcAccessMask(srcAccessMask)
2330 .setDstAccessMask(DstAccessMask(newLayout))
2331 .setOldLayout(oldLayout)
2332 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002333 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2334 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002335 .setImage(image)
2336 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2337
2338 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2339}
2340
2341void Demo::update_data_buffer() {
2342 mat4x4 VP;
2343 mat4x4_mul(VP, projection_matrix, view_matrix);
2344
2345 // Rotate around the Y axis
2346 mat4x4 Model;
2347 mat4x4_dup(Model, model_matrix);
2348 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2349
2350 mat4x4 MVP;
2351 mat4x4_mul(MVP, VP, model_matrix);
2352
Tony-LunarG37af49f2019-12-19 12:04:19 -07002353 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002354}
2355
Karl Schultzb7940402018-05-29 13:09:22 -06002356/* Convert ppm image data from header file into RGBA texture image */
2357#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002358bool 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 -06002359 (void)filename;
2360 char *cPtr;
2361 cPtr = (char *)lunarg_ppm;
2362 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002363 return false;
2364 }
Karl Schultzb7940402018-05-29 13:09:22 -06002365 while (strncmp(cPtr++, "\n", 1))
2366 ;
2367 sscanf(cPtr, "%u %u", width, height);
2368 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002369 return true;
2370 }
Karl Schultzb7940402018-05-29 13:09:22 -06002371 while (strncmp(cPtr++, "\n", 1))
2372 ;
2373 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002374 return false;
2375 }
Karl Schultzb7940402018-05-29 13:09:22 -06002376 while (strncmp(cPtr++, "\n", 1))
2377 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002378 for (int y = 0; y < *height; y++) {
2379 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002380 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002381 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002382 rowPtr[3] = 255; /* Alpha of 1 */
2383 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002384 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002385 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002386 rgba_data += layout->rowPitch;
2387 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002388 return true;
2389}
2390
2391bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2392 // Search memtypes to find first index with those properties
2393 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2394 if ((typeBits & 1) == 1) {
2395 // Type is available, does it match user properties?
2396 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2397 *typeIndex = i;
2398 return true;
2399 }
2400 }
2401 typeBits >>= 1;
2402 }
2403
2404 // No memory types matched, return failure
2405 return false;
2406}
2407
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002408#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002409void Demo::run() {
2410 if (!prepared) {
2411 return;
2412 }
2413
2414 draw();
2415 curFrame++;
2416
Petr Krausd88e4e52019-01-23 18:45:04 +01002417 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002418 PostQuitMessage(validation_error);
2419 }
2420}
2421
2422void Demo::create_window() {
2423 WNDCLASSEX win_class;
2424
2425 // Initialize the window class structure:
2426 win_class.cbSize = sizeof(WNDCLASSEX);
2427 win_class.style = CS_HREDRAW | CS_VREDRAW;
2428 win_class.lpfnWndProc = WndProc;
2429 win_class.cbClsExtra = 0;
2430 win_class.cbWndExtra = 0;
2431 win_class.hInstance = connection; // hInstance
2432 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2433 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2434 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2435 win_class.lpszMenuName = nullptr;
2436 win_class.lpszClassName = name;
2437 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2438
2439 // Register window class:
2440 if (!RegisterClassEx(&win_class)) {
2441 // It didn't work, so try to give a useful error:
2442 printf("Unexpected error trying to start the application!\n");
2443 fflush(stdout);
2444 exit(1);
2445 }
2446
2447 // Create window with the registered class:
2448 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2449 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2450 window = CreateWindowEx(0,
2451 name, // class name
2452 name, // app name
2453 WS_OVERLAPPEDWINDOW | // window style
2454 WS_VISIBLE | WS_SYSMENU,
2455 100, 100, // x/y coords
2456 wr.right - wr.left, // width
2457 wr.bottom - wr.top, // height
2458 nullptr, // handle to parent
2459 nullptr, // handle to menu
2460 connection, // hInstance
2461 nullptr); // no extra parameters
2462
2463 if (!window) {
2464 // It didn't work, so try to give a useful error:
2465 printf("Cannot create a window in which to draw!\n");
2466 fflush(stdout);
2467 exit(1);
2468 }
2469
2470 // Window client area size must be at least 1 pixel high, to prevent
2471 // crash.
2472 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2473 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2474}
2475#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2476
2477void Demo::create_xlib_window() {
2478 const char *display_envar = getenv("DISPLAY");
2479 if (display_envar == nullptr || display_envar[0] == '\0') {
2480 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2481 fflush(stdout);
2482 exit(1);
2483 }
2484
2485 XInitThreads();
2486 display = XOpenDisplay(nullptr);
2487 long visualMask = VisualScreenMask;
2488 int numberOfVisuals;
2489 XVisualInfo vInfoTemplate = {};
2490 vInfoTemplate.screen = DefaultScreen(display);
2491 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2492
2493 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2494
2495 XSetWindowAttributes windowAttributes = {};
2496 windowAttributes.colormap = colormap;
2497 windowAttributes.background_pixel = 0xFFFFFFFF;
2498 windowAttributes.border_pixel = 0;
2499 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2500
2501 xlib_window =
2502 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2503 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2504
2505 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2506 XMapWindow(display, xlib_window);
2507 XFlush(display);
2508 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2509}
2510
2511void Demo::handle_xlib_event(const XEvent *event) {
2512 switch (event->type) {
2513 case ClientMessage:
2514 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2515 quit = true;
2516 }
2517 break;
2518 case KeyPress:
2519 switch (event->xkey.keycode) {
2520 case 0x9: // Escape
2521 quit = true;
2522 break;
2523 case 0x71: // left arrow key
2524 spin_angle -= spin_increment;
2525 break;
2526 case 0x72: // right arrow key
2527 spin_angle += spin_increment;
2528 break;
2529 case 0x41: // space bar
2530 pause = !pause;
2531 break;
2532 }
2533 break;
2534 case ConfigureNotify:
2535 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2536 width = event->xconfigure.width;
2537 height = event->xconfigure.height;
2538 resize();
2539 }
2540 break;
2541 default:
2542 break;
2543 }
2544}
2545
2546void Demo::run_xlib() {
2547 while (!quit) {
2548 XEvent event;
2549
2550 if (pause) {
2551 XNextEvent(display, &event);
2552 handle_xlib_event(&event);
2553 }
2554 while (XPending(display) > 0) {
2555 XNextEvent(display, &event);
2556 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002557 }
2558
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002559 draw();
2560 curFrame++;
2561
Dave Houlton5fa47912018-02-16 11:02:26 -07002562 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2563 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002564 }
2565 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002566}
Tony Barbour153cb062016-12-07 13:43:36 -07002567#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002568
Dave Houlton5fa47912018-02-16 11:02:26 -07002569void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2570 uint8_t event_code = event->response_type & 0x7f;
2571 switch (event_code) {
2572 case XCB_EXPOSE:
2573 // TODO: Resize window
2574 break;
2575 case XCB_CLIENT_MESSAGE:
2576 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2577 quit = true;
2578 }
2579 break;
2580 case XCB_KEY_RELEASE: {
2581 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002582
Dave Houlton5fa47912018-02-16 11:02:26 -07002583 switch (key->detail) {
2584 case 0x9: // Escape
2585 quit = true;
2586 break;
2587 case 0x71: // left arrow key
2588 spin_angle -= spin_increment;
2589 break;
2590 case 0x72: // right arrow key
2591 spin_angle += spin_increment;
2592 break;
2593 case 0x41: // space bar
2594 pause = !pause;
2595 break;
2596 }
2597 } break;
2598 case XCB_CONFIGURE_NOTIFY: {
2599 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2600 if ((width != cfg->width) || (height != cfg->height)) {
2601 width = cfg->width;
2602 height = cfg->height;
2603 resize();
2604 }
2605 } break;
2606 default:
2607 break;
2608 }
2609}
2610
2611void Demo::run_xcb() {
2612 xcb_flush(connection);
2613
2614 while (!quit) {
2615 xcb_generic_event_t *event;
2616
2617 if (pause) {
2618 event = xcb_wait_for_event(connection);
2619 } else {
2620 event = xcb_poll_for_event(connection);
2621 }
2622 while (event) {
2623 handle_xcb_event(event);
2624 free(event);
2625 event = xcb_poll_for_event(connection);
2626 }
2627
2628 draw();
2629 curFrame++;
2630 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2631 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002632 }
2633 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002634}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002635
Dave Houlton5fa47912018-02-16 11:02:26 -07002636void Demo::create_xcb_window() {
2637 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002638
Dave Houlton5fa47912018-02-16 11:02:26 -07002639 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002640
Dave Houlton5fa47912018-02-16 11:02:26 -07002641 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2642 value_list[0] = screen->black_pixel;
2643 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002644
Dave Houlton5fa47912018-02-16 11:02:26 -07002645 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2646 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2647
2648 /* Magic code that will send notification when window is destroyed */
2649 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2650 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2651
2652 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2653 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2654
2655 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2656
2657 free(reply);
2658
2659 xcb_map_window(connection, xcb_window);
2660
2661 // Force the x/y coordinates to 100,100 results are identical in
2662 // consecutive
2663 // runs
2664 const uint32_t coords[] = {100, 100};
2665 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2666}
2667#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2668
2669void Demo::run() {
2670 while (!quit) {
2671 if (pause) {
2672 wl_display_dispatch(display);
2673 } else {
2674 wl_display_dispatch_pending(display);
2675 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002676 draw();
2677 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002678 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002679 quit = true;
2680 }
2681 }
2682 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002683}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002684
Dave Houlton5fa47912018-02-16 11:02:26 -07002685void Demo::create_window() {
2686 window = wl_compositor_create_surface(compositor);
2687 if (!window) {
2688 printf("Can not create wayland_surface from compositor!\n");
2689 fflush(stdout);
2690 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002691 }
2692
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002693 shell_surface = wl_shell_get_shell_surface(shell, window);
2694 if (!shell_surface) {
2695 printf("Can not get shell_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002696 fflush(stdout);
2697 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002698 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002699
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002700 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2701 wl_shell_surface_set_toplevel(shell_surface);
2702 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
Dave Houlton5fa47912018-02-16 11:02:26 -07002703}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002704#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002705void Demo::run() {
2706 draw();
2707 curFrame++;
2708 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2709 quit = true;
2710 }
2711}
Damien Leone600c3052017-01-31 10:26:07 -07002712#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2713
Dave Houlton5fa47912018-02-16 11:02:26 -07002714vk::Result Demo::create_display_surface() {
2715 vk::Result result;
2716 uint32_t display_count;
2717 uint32_t mode_count;
2718 uint32_t plane_count;
2719 vk::DisplayPropertiesKHR display_props;
2720 vk::DisplayKHR display;
2721 vk::DisplayModePropertiesKHR mode_props;
2722 vk::DisplayPlanePropertiesKHR *plane_props;
2723 vk::Bool32 found_plane = VK_FALSE;
2724 uint32_t plane_index;
2725 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002726
Dave Houlton5fa47912018-02-16 11:02:26 -07002727 // Get the first display
2728 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2729 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002730
Dave Houlton5fa47912018-02-16 11:02:26 -07002731 if (display_count == 0) {
2732 printf("Cannot find any display!\n");
2733 fflush(stdout);
2734 exit(1);
2735 }
2736
2737 display_count = 1;
2738 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2739 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2740
2741 display = display_props.display;
2742
2743 // Get the first mode of the display
2744 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2745 VERIFY(result == vk::Result::eSuccess);
2746
2747 if (mode_count == 0) {
2748 printf("Cannot find any mode for the display!\n");
2749 fflush(stdout);
2750 exit(1);
2751 }
2752
2753 mode_count = 1;
2754 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2755 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2756
2757 // Get the list of planes
2758 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2759 VERIFY(result == vk::Result::eSuccess);
2760
2761 if (plane_count == 0) {
2762 printf("Cannot find any plane!\n");
2763 fflush(stdout);
2764 exit(1);
2765 }
2766
2767 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2768 VERIFY(plane_props != nullptr);
2769
2770 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2771 VERIFY(result == vk::Result::eSuccess);
2772
2773 // Find a plane compatible with the display
2774 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2775 uint32_t supported_count;
2776 vk::DisplayKHR *supported_displays;
2777
2778 // Disqualify planes that are bound to a different display
2779 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2780 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002781 }
2782
Dave Houlton5fa47912018-02-16 11:02:26 -07002783 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002784 VERIFY(result == vk::Result::eSuccess);
2785
Dave Houlton5fa47912018-02-16 11:02:26 -07002786 if (supported_count == 0) {
2787 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002788 }
2789
Dave Houlton5fa47912018-02-16 11:02:26 -07002790 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2791 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002792
Dave Houlton5fa47912018-02-16 11:02:26 -07002793 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002794 VERIFY(result == vk::Result::eSuccess);
2795
Dave Houlton5fa47912018-02-16 11:02:26 -07002796 for (uint32_t i = 0; i < supported_count; i++) {
2797 if (supported_displays[i] == display) {
2798 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002799 break;
2800 }
2801 }
2802
Dave Houlton5fa47912018-02-16 11:02:26 -07002803 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002804
Dave Houlton5fa47912018-02-16 11:02:26 -07002805 if (found_plane) {
2806 break;
Damien Leone600c3052017-01-31 10:26:07 -07002807 }
2808 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002809
2810 if (!found_plane) {
2811 printf("Cannot find a plane compatible with the display!\n");
2812 fflush(stdout);
2813 exit(1);
2814 }
2815
2816 free(plane_props);
2817
2818 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2819 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2820 // Find a supported alpha mode
2821 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2822 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2823 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2824 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2825 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2826 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2827 };
2828 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2829 if (planeCaps.supportedAlpha & alphaModes[i]) {
2830 alphaMode = alphaModes[i];
2831 break;
2832 }
2833 }
2834
2835 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2836 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2837
2838 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2839 .setDisplayMode(mode_props.displayMode)
2840 .setPlaneIndex(plane_index)
2841 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2842 .setGlobalAlpha(1.0f)
2843 .setAlphaMode(alphaMode)
2844 .setImageExtent(image_extent);
2845
2846 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2847}
2848
2849void Demo::run_display() {
2850 while (!quit) {
2851 draw();
2852 curFrame++;
2853
Petr Krausd88e4e52019-01-23 18:45:04 +01002854 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002855 quit = true;
2856 }
2857 }
2858}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002859#endif
2860
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002861#if _WIN32
2862// Include header required for parsing the command line options.
2863#include <shellapi.h>
2864
2865Demo demo;
2866
2867// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002868LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2869 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002870 case WM_CLOSE:
2871 PostQuitMessage(validation_error);
2872 break;
2873 case WM_PAINT:
2874 demo.run();
2875 break;
2876 case WM_GETMINMAXINFO: // set window's minimum size
2877 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2878 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002879 case WM_ERASEBKGND:
2880 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002881 case WM_SIZE:
2882 // Resize the application to the new window size, except when
2883 // it was minimized. Vulkan doesn't support images or swapchains
2884 // with width=0 and height=0.
2885 if (wParam != SIZE_MINIMIZED) {
2886 demo.width = lParam & 0xffff;
2887 demo.height = (lParam & 0xffff0000) >> 16;
2888 demo.resize();
2889 }
2890 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002891 case WM_KEYDOWN:
2892 switch (wParam) {
2893 case VK_ESCAPE:
2894 PostQuitMessage(validation_error);
2895 break;
2896 case VK_LEFT:
2897 demo.spin_angle -= demo.spin_increment;
2898 break;
2899 case VK_RIGHT:
2900 demo.spin_angle += demo.spin_increment;
2901 break;
2902 case VK_SPACE:
2903 demo.pause = !demo.pause;
2904 break;
2905 }
2906 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002907 default:
2908 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002909 }
2910
2911 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2912}
2913
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002914int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002915 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002916 MSG msg; // message
2917 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002918 int argc;
2919 char **argv;
2920
Jamie Madillb2ff6502017-03-15 16:17:46 -04002921 // Ensure wParam is initialized.
2922 msg.wParam = 0;
2923
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002924 // Use the CommandLine functions to get the command line arguments.
2925 // Unfortunately, Microsoft outputs
2926 // this information as wide characters for Unicode, and we simply want the
2927 // Ascii version to be compatible
2928 // with the non-Windows side. So, we have to convert the information to
2929 // Ascii character strings.
2930 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002931 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002932 argc = 0;
2933 }
2934
Jeremy Hayes9d304782016-10-09 11:48:12 -06002935 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002936 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002937 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002938 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002939 } else {
2940 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002941 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2942 size_t numConverted = 0;
2943
2944 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06002945 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002946 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002947 }
2948 }
2949 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06002950 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002951 argv = nullptr;
2952 }
2953
2954 demo.init(argc, argv);
2955
2956 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06002957 if (argc > 0 && argv != nullptr) {
2958 for (int iii = 0; iii < argc; iii++) {
2959 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002960 free(argv[iii]);
2961 }
2962 }
2963 free(argv);
2964 }
2965
2966 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07002967 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002968 demo.create_window();
2969 demo.init_vk_swapchain();
2970
2971 demo.prepare();
2972
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002973 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002974
2975 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06002976 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01002977 if (demo.pause) {
2978 const BOOL succ = WaitMessage();
2979
2980 if (!succ) {
2981 const auto &suppress_popups = demo.suppress_popups;
2982 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
2983 }
2984 }
2985
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002986 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002987 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002988 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002989 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06002990 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002991 /* Translate and dispatch to event queue*/
2992 TranslateMessage(&msg);
2993 DispatchMessage(&msg);
2994 }
2995 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2996 }
2997
2998 demo.cleanup();
2999
3000 return (int)msg.wParam;
3001}
3002
3003#elif __linux__
3004
Jeremy Hayes9d304782016-10-09 11:48:12 -06003005int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003006 Demo demo;
3007
3008 demo.init(argc, argv);
3009
Tony Barbour153cb062016-12-07 13:43:36 -07003010#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003011 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003012#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003013 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003014 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003015#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003016 demo.create_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003017#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003018
3019 demo.init_vk_swapchain();
3020
3021 demo.prepare();
3022
Tony Barbour153cb062016-12-07 13:43:36 -07003023#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003024 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003025#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003026 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003027#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003028 demo.run();
Damien Leone600c3052017-01-31 10:26:07 -07003029#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3030 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003031#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003032
3033 demo.cleanup();
3034
3035 return validation_error;
3036}
3037
Bill Hollings0a0625a2019-07-15 17:39:18 -04003038#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003039
3040// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003041static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003042 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003043 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003044 demo.init_vk_swapchain();
3045 demo.prepare();
3046 demo.spin_angle = 0.4f;
3047}
3048
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003049#else
3050#error "Platform not supported"
3051#endif