blob: e270a8dde3b81fc79a6997ae4363bd9e500508ac [file] [log] [blame]
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09001/*
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.
Ian Elliottd940ca22017-03-22 08:31:27 -06005 *
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: Chia-I Wu <olv@lunarg.com>
19 * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
20 * Author: Ian Elliott <ian@LunarG.com>
21 * Author: Ian Elliott <ianelliott@google.com>
22 * Author: Jon Ashburn <jon@lunarg.com>
23 * Author: Gwan-gyeong Mun <elongbug@gmail.com>
24 * Author: Tony Barbour <tony@LunarG.com>
25 * Author: Bill Hollings <bill.hollings@brenwill.com>
26 */
Karl Schultze4dc75c2016-02-02 15:37:51 -070027
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -060028#define _GNU_SOURCE
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060029#include <stdio.h>
Ian Elliottd940ca22017-03-22 08:31:27 -060030#include <stdarg.h>
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060031#include <stdlib.h>
32#include <string.h>
33#include <stdbool.h>
34#include <assert.h>
Courtney Goeltzenleuchteraf1951c2015-12-01 14:11:38 -070035#include <signal.h>
Mun Gwan-gyeong22533892016-08-20 14:46:22 +090036#if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
Tony Barbour2593b182016-04-19 10:57:58 -060037#include <X11/Xutil.h>
Joey Bzdek15eb0702017-06-07 09:40:36 -060038#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
39#include <linux/input.h>
Manuel Stoecklac939332019-06-26 20:55:53 -040040#include "xdg-shell-client-header.h"
41#include "xdg-decoration-client-header.h"
Tony Barbour2593b182016-04-19 10:57:58 -060042#endif
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060043
Ian Elliott639ca472015-04-16 15:23:05 -060044#ifdef _WIN32
Biswapriyo Nathffe404f2020-08-25 01:47:41 +053045#ifdef _MSC_VER
Ian Elliott639ca472015-04-16 15:23:05 -060046#pragma comment(linker, "/subsystem:windows")
Biswapriyo Nathc472fa22020-08-25 23:49:34 +053047#endif // MSVC
Ian Elliott639ca472015-04-16 15:23:05 -060048#define APP_NAME_STR_LEN 80
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070049#endif // _WIN32
Ian Elliott639ca472015-04-16 15:23:05 -060050
Cody Northrop8707a6e2016-04-26 19:59:19 -060051#ifdef ANDROID
52#include "vulkan_wrapper.h"
53#else
David Pinedoc5193c12015-11-06 12:54:48 -070054#include <vulkan/vulkan.h>
Cody Northrop8707a6e2016-04-26 19:59:19 -060055#endif
Ian Elliottb08e0d92015-11-20 11:55:46 -070056
David Pinedo541526f2015-11-24 09:00:24 -070057#include <vulkan/vk_sdk_platform.h>
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -060058#include "linmath.h"
Mark Lobodzinski0edf1382018-04-10 15:40:04 -060059#include "object_type_string_helper.h"
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -060060
Ian Elliottd940ca22017-03-22 08:31:27 -060061#include "gettime.h"
62#include "inttypes.h"
63#define MILLION 1000000L
64#define BILLION 1000000000L
65
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060066#define DEMO_TEXTURE_COUNT 1
Lenny Komowffe446c2018-11-19 17:08:04 -070067#define APP_SHORT_NAME "vkcube"
68#define APP_LONG_NAME "Vulkan Cube"
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060069
Tony Barbour66a56c32016-09-21 13:10:56 -060070// Allow a maximum of two outstanding presentation operations.
71#define FRAME_LAG 2
72
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -060073#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
74
Tony Barbourfdc2d352015-04-22 09:02:32 -060075#if defined(NDEBUG) && defined(__GNUC__)
76#define U_ASSERT_ONLY __attribute__((unused))
77#else
78#define U_ASSERT_ONLY
79#endif
80
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +090081#if defined(__GNUC__)
82#define UNUSED __attribute__((unused))
83#else
84#define UNUSED
85#endif
86
Ian Elliott07264132015-04-28 11:35:02 -060087#ifdef _WIN32
Tony Barbour602ca4f2016-09-12 14:02:43 -060088bool in_callback = false;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070089#define ERR_EXIT(err_msg, err_class) \
90 do { \
91 if (!demo->suppress_popups) MessageBox(NULL, err_msg, err_class, MB_OK); \
92 exit(1); \
Karl Schultze4dc75c2016-02-02 15:37:51 -070093 } while (0)
Ian Elliottd940ca22017-03-22 08:31:27 -060094void DbgMsg(char *fmt, ...) {
95 va_list va;
96 va_start(va, fmt);
Mike Weiblene9847ff2019-06-27 15:18:32 -060097 vprintf(fmt, va);
Ian Elliottd940ca22017-03-22 08:31:27 -060098 va_end(va);
Mike Weiblene9847ff2019-06-27 15:18:32 -060099 fflush(stdout);
Ian Elliottd940ca22017-03-22 08:31:27 -0600100}
Ian Elliott07264132015-04-28 11:35:02 -0600101
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500102#elif defined __ANDROID__
103#include <android/log.h>
Jeremy Kniager979b5312019-11-22 14:55:57 -0700104#define ERR_EXIT(err_msg, err_class) \
105 do { \
Lenny Komowffe446c2018-11-19 17:08:04 -0700106 ((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", err_msg)); \
Jeremy Kniager979b5312019-11-22 14:55:57 -0700107 exit(1); \
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500108 } while (0)
Ian Elliottd940ca22017-03-22 08:31:27 -0600109#ifdef VARARGS_WORKS_ON_ANDROID
110void DbgMsg(const char *fmt, ...) {
111 va_list va;
112 va_start(va, fmt);
Lenny Komowffe446c2018-11-19 17:08:04 -0700113 __android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, va);
Ian Elliottd940ca22017-03-22 08:31:27 -0600114 va_end(va);
115}
116#else // VARARGS_WORKS_ON_ANDROID
Jeremy Kniager979b5312019-11-22 14:55:57 -0700117#define DbgMsg(fmt, ...) \
118 do { \
Lenny Komowffe446c2018-11-19 17:08:04 -0700119 ((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, ##__VA_ARGS__)); \
Ian Elliottd940ca22017-03-22 08:31:27 -0600120 } while (0)
121#endif // VARARGS_WORKS_ON_ANDROID
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500122#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700123#define ERR_EXIT(err_msg, err_class) \
124 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -0800125 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700126 fflush(stdout); \
127 exit(1); \
Karl Schultze4dc75c2016-02-02 15:37:51 -0700128 } while (0)
Ian Elliottd940ca22017-03-22 08:31:27 -0600129void DbgMsg(char *fmt, ...) {
130 va_list va;
131 va_start(va, fmt);
Mike Weiblene9847ff2019-06-27 15:18:32 -0600132 vprintf(fmt, va);
Ian Elliottd940ca22017-03-22 08:31:27 -0600133 va_end(va);
Mike Weiblene9847ff2019-06-27 15:18:32 -0600134 fflush(stdout);
Ian Elliottd940ca22017-03-22 08:31:27 -0600135}
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500136#endif
Ian Elliott07264132015-04-28 11:35:02 -0600137
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700138#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \
139 { \
140 demo->fp##entrypoint = (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \
141 if (demo->fp##entrypoint == NULL) { \
142 ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint, "vkGetInstanceProcAddr Failure"); \
143 } \
Karl Schultze4dc75c2016-02-02 15:37:51 -0700144 }
Ian Elliottaaae5352015-07-06 14:27:58 -0600145
Jon Ashburn7d8342c2015-10-08 15:58:23 -0600146static PFN_vkGetDeviceProcAddr g_gdpa = NULL;
147
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700148#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \
149 { \
150 if (!g_gdpa) g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(demo->inst, "vkGetDeviceProcAddr"); \
151 demo->fp##entrypoint = (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint); \
152 if (demo->fp##entrypoint == NULL) { \
153 ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint, "vkGetDeviceProcAddr Failure"); \
154 } \
Karl Schultze4dc75c2016-02-02 15:37:51 -0700155 }
Ian Elliott673898b2015-06-22 15:07:49 -0600156
Courtney Goeltzenleuchter97db1c12014-10-30 15:14:16 -0600157/*
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -0700158 * structure to track all objects related to a texture.
159 */
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600160struct texture_object {
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600161 VkSampler sampler;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -0700162
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600163 VkImage image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600164 VkBuffer buffer;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600165 VkImageLayout imageLayout;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600166
Chia-I Wua8fe78a2015-10-27 18:04:07 +0800167 VkMemoryAllocateInfo mem_alloc;
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -0500168 VkDeviceMemory mem;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600169 VkImageView view;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -0700170 int32_t tex_width, tex_height;
171};
172
Karl Schultze4dc75c2016-02-02 15:37:51 -0700173static char *tex_files[] = {"lunarg.ppm"};
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600174
Karl Schultz0218c002016-03-22 17:06:13 -0600175static int validation_error = 0;
176
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600177struct vktexcube_vs_uniform {
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600178 // Must start with MVP
Karl Schultze4dc75c2016-02-02 15:37:51 -0700179 float mvp[4][4];
180 float position[12 * 3][4];
181 float attr[12 * 3][4];
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600182};
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600183
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600184//--------------------------------------------------------------------------------------
185// Mesh and VertexFormat Data
186//--------------------------------------------------------------------------------------
Karl Schultze4dc75c2016-02-02 15:37:51 -0700187// clang-format off
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -0600188static const float g_vertex_buffer_data[] = {
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800189 -1.0f,-1.0f,-1.0f, // -X side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600190 -1.0f,-1.0f, 1.0f,
191 -1.0f, 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800192 -1.0f, 1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600193 -1.0f, 1.0f,-1.0f,
194 -1.0f,-1.0f,-1.0f,
195
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800196 -1.0f,-1.0f,-1.0f, // -Z side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600197 1.0f, 1.0f,-1.0f,
198 1.0f,-1.0f,-1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800199 -1.0f,-1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600200 -1.0f, 1.0f,-1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600201 1.0f, 1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600202
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800203 -1.0f,-1.0f,-1.0f, // -Y side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600204 1.0f,-1.0f,-1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600205 1.0f,-1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800206 -1.0f,-1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600207 1.0f,-1.0f, 1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600208 -1.0f,-1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600209
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800210 -1.0f, 1.0f,-1.0f, // +Y side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600211 -1.0f, 1.0f, 1.0f,
212 1.0f, 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800213 -1.0f, 1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600214 1.0f, 1.0f, 1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600215 1.0f, 1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600216
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800217 1.0f, 1.0f,-1.0f, // +X side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600218 1.0f, 1.0f, 1.0f,
219 1.0f,-1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800220 1.0f,-1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600221 1.0f,-1.0f,-1.0f,
222 1.0f, 1.0f,-1.0f,
223
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800224 -1.0f, 1.0f, 1.0f, // +Z side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600225 -1.0f,-1.0f, 1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600226 1.0f, 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800227 -1.0f,-1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600228 1.0f,-1.0f, 1.0f,
229 1.0f, 1.0f, 1.0f,
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600230};
231
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -0600232static const float g_uv_buffer_data[] = {
Rene Lindsay76867e82016-07-29 10:49:11 -0700233 0.0f, 1.0f, // -X side
234 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800235 1.0f, 0.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800236 1.0f, 0.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600237 0.0f, 0.0f,
238 0.0f, 1.0f,
239
Rene Lindsay76867e82016-07-29 10:49:11 -0700240 1.0f, 1.0f, // -Z side
241 0.0f, 0.0f,
242 0.0f, 1.0f,
243 1.0f, 1.0f,
244 1.0f, 0.0f,
245 0.0f, 0.0f,
246
247 1.0f, 0.0f, // -Y side
248 1.0f, 1.0f,
249 0.0f, 1.0f,
250 1.0f, 0.0f,
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -0600251 0.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800252 0.0f, 0.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600253
Rene Lindsay76867e82016-07-29 10:49:11 -0700254 1.0f, 0.0f, // +Y side
255 0.0f, 0.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800256 0.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600257 1.0f, 0.0f,
Rene Lindsay76867e82016-07-29 10:49:11 -0700258 0.0f, 1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600259 1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600260
Rene Lindsay76867e82016-07-29 10:49:11 -0700261 1.0f, 0.0f, // +X side
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800262 0.0f, 0.0f,
Rene Lindsay76867e82016-07-29 10:49:11 -0700263 0.0f, 1.0f,
264 0.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600265 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800266 1.0f, 0.0f,
Rene Lindsay76867e82016-07-29 10:49:11 -0700267
268 0.0f, 0.0f, // +Z side
269 0.0f, 1.0f,
270 1.0f, 0.0f,
271 0.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600272 1.0f, 1.0f,
Rene Lindsay76867e82016-07-29 10:49:11 -0700273 1.0f, 0.0f,
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600274};
Karl Schultze4dc75c2016-02-02 15:37:51 -0700275// clang-format on
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600276
Karl Schultze4dc75c2016-02-02 15:37:51 -0700277void dumpMatrix(const char *note, mat4x4 MVP) {
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600278 int i;
279
280 printf("%s: \n", note);
Karl Schultze4dc75c2016-02-02 15:37:51 -0700281 for (i = 0; i < 4; i++) {
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600282 printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]);
283 }
284 printf("\n");
285 fflush(stdout);
286}
287
Karl Schultze4dc75c2016-02-02 15:37:51 -0700288void dumpVec4(const char *note, vec4 vector) {
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600289 printf("%s: \n", note);
Karl Schultze4dc75c2016-02-02 15:37:51 -0700290 printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600291 printf("\n");
292 fflush(stdout);
293}
294
Charles Giessen5f3ce242022-04-11 14:39:06 -0600295char const *to_string(VkPhysicalDeviceType const type) {
296 switch (type) {
297 case VK_PHYSICAL_DEVICE_TYPE_OTHER:
298 return "Other";
299 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
300 return "IntegratedGpu";
301 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
302 return "DiscreteGpu";
303 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
304 return "VirtualGpu";
305 case VK_PHYSICAL_DEVICE_TYPE_CPU:
306 return "Cpu";
307 default:
308 return "Unknown";
Jeremy Hayes5f9e5f12022-02-09 15:04:42 -0700309 }
310}
311
Mark Lobodzinski4c62d002016-05-19 17:22:25 -0600312typedef struct {
Ian Elliottaaae5352015-07-06 14:27:58 -0600313 VkImage image;
Chia-I Wua8fe78a2015-10-27 18:04:07 +0800314 VkCommandBuffer cmd;
Tony Barbour22e06272016-09-07 16:07:56 -0600315 VkCommandBuffer graphics_to_present_cmd;
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -0600316 VkImageView view;
Tony Barboura72d9492017-01-11 13:35:09 -0700317 VkBuffer uniform_buffer;
318 VkDeviceMemory uniform_memory;
Tony-LunarG37af49f2019-12-19 12:04:19 -0700319 void *uniform_memory_ptr;
Tony Barboura72d9492017-01-11 13:35:09 -0700320 VkFramebuffer framebuffer;
321 VkDescriptorSet descriptor_set;
Tony Barboura72d9492017-01-11 13:35:09 -0700322} SwapchainImageResources;
Ian Elliottaaae5352015-07-06 14:27:58 -0600323
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600324struct demo {
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500325#if defined(VK_USE_PLATFORM_WIN32_KHR)
Ian Elliott639ca472015-04-16 15:23:05 -0600326#define APP_NAME_STR_LEN 80
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700327 HINSTANCE connection; // hInstance - Windows Instance
328 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
329 HWND window; // hWnd - window handle
330 POINT minsize; // minimum window size
Tony Barbour153cb062016-12-07 13:43:36 -0700331#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700332 Display *display;
Tony Barbour2593b182016-04-19 10:57:58 -0600333 Window xlib_window;
334 Atom xlib_wm_delete_window;
Tony Barbour153cb062016-12-07 13:43:36 -0700335#elif defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700336 Display *display;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600337 xcb_connection_t *connection;
338 xcb_screen_t *screen;
Tony Barbour2593b182016-04-19 10:57:58 -0600339 xcb_window_t xcb_window;
Chia-I Wucbb564e2015-04-16 22:02:10 +0800340 xcb_intern_atom_reply_t *atom_wm_delete_window;
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +0900341#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
342 struct wl_display *display;
343 struct wl_registry *registry;
344 struct wl_compositor *compositor;
345 struct wl_surface *window;
Manuel Stoecklac939332019-06-26 20:55:53 -0400346 struct xdg_wm_base *xdg_wm_base;
347 struct zxdg_decoration_manager_v1 *xdg_decoration_mgr;
348 struct zxdg_toplevel_decoration_v1 *toplevel_decoration;
349 struct xdg_surface *xdg_surface;
350 int xdg_surface_has_been_configured;
351 struct xdg_toplevel *xdg_toplevel;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600352 struct wl_seat *seat;
353 struct wl_pointer *pointer;
354 struct wl_keyboard *keyboard;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200355#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
356 IDirectFB *dfb;
357 IDirectFBSurface *window;
358 IDirectFBEventBuffer *event_buffer;
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500359#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
Mike Schuchardt837d5162018-03-08 12:57:02 -0700360 struct ANativeWindow *window;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400361#elif defined(VK_USE_PLATFORM_METAL_EXT)
362 void *caMetalLayer;
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500363#endif
Ian Elliottb08e0d92015-11-20 11:55:46 -0700364 VkSurfaceKHR surface;
Cody Northrop1fedb212015-05-28 11:27:16 -0600365 bool prepared;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -0700366 bool use_staging_buffer;
Tony Barbour22e06272016-09-07 16:07:56 -0600367 bool separate_present_queue;
Jeremy Kniager602e4182018-01-19 10:52:34 -0700368 bool is_minimized;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000369 int32_t gpu_number;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600370
Ian Elliott53622a72017-03-28 11:06:33 -0600371 bool VK_KHR_incremental_present_enabled;
372
Ian Elliottd940ca22017-03-22 08:31:27 -0600373 bool VK_GOOGLE_display_timing_enabled;
374 bool syncd_with_actual_presents;
375 uint64_t refresh_duration;
376 uint64_t refresh_duration_multiplier;
377 uint64_t target_IPD; // image present duration (inverse of frame rate)
378 uint64_t prev_desired_present_time;
379 uint32_t next_present_id;
380 uint32_t last_early_id; // 0 if no early images
381 uint32_t last_late_id; // 0 if no late images
382
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600383 VkInstance inst;
Tony Barbour72304ef2015-04-16 15:59:00 -0600384 VkPhysicalDevice gpu;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600385 VkDevice device;
Tony Barboura2a67812016-07-18 13:21:06 -0600386 VkQueue graphics_queue;
387 VkQueue present_queue;
388 uint32_t graphics_queue_family_index;
389 uint32_t present_queue_family_index;
Tony Barbour66a56c32016-09-21 13:10:56 -0600390 VkSemaphore image_acquired_semaphores[FRAME_LAG];
391 VkSemaphore draw_complete_semaphores[FRAME_LAG];
392 VkSemaphore image_ownership_semaphores[FRAME_LAG];
Tony Barbourecf1b2b2015-06-24 16:06:58 -0600393 VkPhysicalDeviceProperties gpu_props;
Cody Northrop4d3c11d2015-08-03 17:04:53 -0600394 VkQueueFamilyProperties *queue_props;
Mark Lobodzinskieadf9982015-07-02 16:49:40 -0600395 VkPhysicalDeviceMemoryProperties memory_properties;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600396
Tony Barbourda2bad52016-01-22 14:36:40 -0700397 uint32_t enabled_extension_count;
398 uint32_t enabled_layer_count;
399 char *extension_names[64];
Karl Schultz5b423ea2016-06-20 19:08:43 -0600400 char *enabled_layers[64];
Tony Barbourda2bad52016-01-22 14:36:40 -0700401
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600402 int width, height;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600403 VkFormat format;
Ian Elliotta0781972015-08-21 15:09:33 -0600404 VkColorSpaceKHR color_space;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600405
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700406 PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR;
407 PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR;
408 PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR;
409 PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR;
Ian Elliotta0781972015-08-21 15:09:33 -0600410 PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR;
411 PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR;
412 PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR;
413 PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR;
414 PFN_vkQueuePresentKHR fpQueuePresentKHR;
Ian Elliottd940ca22017-03-22 08:31:27 -0600415 PFN_vkGetRefreshCycleDurationGOOGLE fpGetRefreshCycleDurationGOOGLE;
416 PFN_vkGetPastPresentationTimingGOOGLE fpGetPastPresentationTimingGOOGLE;
Ian Elliotta0781972015-08-21 15:09:33 -0600417 uint32_t swapchainImageCount;
Ian Elliottcf074d32015-10-16 18:02:43 -0600418 VkSwapchainKHR swapchain;
Tony Barboura72d9492017-01-11 13:35:09 -0700419 SwapchainImageResources *swapchain_image_resources;
Tony Barbour291d57b2016-10-21 14:47:07 -0600420 VkPresentModeKHR presentMode;
Tony Barbour66a56c32016-09-21 13:10:56 -0600421 VkFence fences[FRAME_LAG];
Tony Barbour66a56c32016-09-21 13:10:56 -0600422 int frame_index;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600423
Chia-I Wua8fe78a2015-10-27 18:04:07 +0800424 VkCommandPool cmd_pool;
Tony Barbour22e06272016-09-07 16:07:56 -0600425 VkCommandPool present_cmd_pool;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600426
427 struct {
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600428 VkFormat format;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600429
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600430 VkImage image;
Chia-I Wua8fe78a2015-10-27 18:04:07 +0800431 VkMemoryAllocateInfo mem_alloc;
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -0500432 VkDeviceMemory mem;
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -0600433 VkImageView view;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600434 } depth;
435
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600436 struct texture_object textures[DEMO_TEXTURE_COUNT];
Tony Barbour16156cb2016-10-19 14:15:49 -0600437 struct texture_object staging_texture;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600438
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700439 VkCommandBuffer cmd; // Buffer for initialization commands
Mark Lobodzinski1cfc7722015-04-17 14:11:39 -0500440 VkPipelineLayout pipeline_layout;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600441 VkDescriptorSetLayout desc_layout;
Jon Ashburnc4ab7af2015-07-09 15:02:25 -0600442 VkPipelineCache pipelineCache;
Chia-I Wuf973e322015-07-08 13:34:24 +0800443 VkRenderPass render_pass;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600444 VkPipeline pipeline;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600445
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600446 mat4x4 projection_matrix;
447 mat4x4 view_matrix;
448 mat4x4 model_matrix;
449
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -0600450 float spin_angle;
451 float spin_increment;
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -0600452 bool pause;
453
Tony Barbourb6dba5c2015-07-21 09:04:41 -0600454 VkShaderModule vert_shader_module;
455 VkShaderModule frag_shader_module;
456
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600457 VkDescriptorPool desc_pool;
Chia-I Wuf973e322015-07-08 13:34:24 +0800458
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600459 bool quit;
David Pinedo2bb7c932015-06-18 17:03:14 -0600460 int32_t curFrame;
461 int32_t frameCount;
Tony Barbour3dddd5d2015-04-29 16:19:20 -0600462 bool validate;
Tobin Ehlis4eb29d62017-03-14 11:29:01 -0600463 bool validate_checks_disabled;
Courtney Goeltzenleuchter03f4b772015-07-22 11:03:51 -0600464 bool use_break;
lenny-lunargfbe22392016-06-06 11:07:53 -0600465 bool suppress_popups;
Mark Young43c08f82021-11-30 16:38:25 -0700466 bool force_errors;
Mark Young66510e52017-11-10 10:05:14 -0700467
468 PFN_vkCreateDebugUtilsMessengerEXT CreateDebugUtilsMessengerEXT;
469 PFN_vkDestroyDebugUtilsMessengerEXT DestroyDebugUtilsMessengerEXT;
470 PFN_vkSubmitDebugUtilsMessageEXT SubmitDebugUtilsMessageEXT;
471 PFN_vkCmdBeginDebugUtilsLabelEXT CmdBeginDebugUtilsLabelEXT;
472 PFN_vkCmdEndDebugUtilsLabelEXT CmdEndDebugUtilsLabelEXT;
473 PFN_vkCmdInsertDebugUtilsLabelEXT CmdInsertDebugUtilsLabelEXT;
474 PFN_vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT;
475 VkDebugUtilsMessengerEXT dbg_messenger;
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -0600476
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -0600477 uint32_t current_buffer;
Tony Barbourab2a0362016-09-06 11:40:12 -0600478 uint32_t queue_family_count;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600479};
480
Mark Young66510e52017-11-10 10:05:14 -0700481VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
482 VkDebugUtilsMessageTypeFlagsEXT messageType,
483 const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
484 void *pUserData) {
485 char prefix[64] = "";
486 char *message = (char *)malloc(strlen(pCallbackData->pMessage) + 5000);
lenny-lunargfbe22392016-06-06 11:07:53 -0600487 assert(message);
Mark Young66510e52017-11-10 10:05:14 -0700488 struct demo *demo = (struct demo *)pUserData;
lenny-lunargfbe22392016-06-06 11:07:53 -0600489
Mark Young66510e52017-11-10 10:05:14 -0700490 if (demo->use_break) {
491#ifndef WIN32
492 raise(SIGTRAP);
493#else
494 DebugBreak();
495#endif
496 }
497
498 if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
499 strcat(prefix, "VERBOSE : ");
500 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
501 strcat(prefix, "INFO : ");
502 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
503 strcat(prefix, "WARNING : ");
504 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
505 strcat(prefix, "ERROR : ");
506 }
507
508 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
509 strcat(prefix, "GENERAL");
lenny-lunargfbe22392016-06-06 11:07:53 -0600510 } else {
Mark Young66510e52017-11-10 10:05:14 -0700511 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
512 strcat(prefix, "VALIDATION");
513 validation_error = 1;
514 }
515 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
516 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
517 strcat(prefix, "|");
518 }
519 strcat(prefix, "PERFORMANCE");
520 }
521 }
522
523 sprintf(message, "%s - Message Id Number: %d | Message Id Name: %s\n\t%s\n", prefix, pCallbackData->messageIdNumber,
524 pCallbackData->pMessageIdName, pCallbackData->pMessage);
525 if (pCallbackData->objectCount > 0) {
526 char tmp_message[500];
527 sprintf(tmp_message, "\n\tObjects - %d\n", pCallbackData->objectCount);
528 strcat(message, tmp_message);
529 for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
530 if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
531 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p, Name \"%s\"\n", object,
Mark Young44212682018-02-21 15:29:41 -0700532 string_VkObjectType(pCallbackData->pObjects[object].objectType),
Mark Young66510e52017-11-10 10:05:14 -0700533 (void *)(pCallbackData->pObjects[object].objectHandle), pCallbackData->pObjects[object].pObjectName);
534 } else {
535 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p\n", object,
Mark Young44212682018-02-21 15:29:41 -0700536 string_VkObjectType(pCallbackData->pObjects[object].objectType),
Mark Young66510e52017-11-10 10:05:14 -0700537 (void *)(pCallbackData->pObjects[object].objectHandle));
538 }
539 strcat(message, tmp_message);
540 }
541 }
542 if (pCallbackData->cmdBufLabelCount > 0) {
543 char tmp_message[500];
544 sprintf(tmp_message, "\n\tCommand Buffer Labels - %d\n", pCallbackData->cmdBufLabelCount);
545 strcat(message, tmp_message);
546 for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
547 sprintf(tmp_message, "\t\tLabel[%d] - %s { %f, %f, %f, %f}\n", cmd_buf_label,
548 pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName, pCallbackData->pCmdBufLabels[cmd_buf_label].color[0],
549 pCallbackData->pCmdBufLabels[cmd_buf_label].color[1], pCallbackData->pCmdBufLabels[cmd_buf_label].color[2],
550 pCallbackData->pCmdBufLabels[cmd_buf_label].color[3]);
551 strcat(message, tmp_message);
552 }
lenny-lunargfbe22392016-06-06 11:07:53 -0600553 }
554
555#ifdef _WIN32
Cody Northropaf28a532016-09-27 10:50:57 -0600556
Tony Barbour602ca4f2016-09-12 14:02:43 -0600557 in_callback = true;
Jeremy Kniager979b5312019-11-22 14:55:57 -0700558 if (!demo->suppress_popups) MessageBox(NULL, message, "Alert", MB_OK);
Tony Barbour602ca4f2016-09-12 14:02:43 -0600559 in_callback = false;
Cody Northropaf28a532016-09-27 10:50:57 -0600560
Cody Northropc5e5a8c2016-09-26 21:05:00 -0600561#elif defined(ANDROID)
Cody Northropaf28a532016-09-27 10:50:57 -0600562
Mike Schuchardt837d5162018-03-08 12:57:02 -0700563 if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
Jeremy Kniager979b5312019-11-22 14:55:57 -0700564 __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
Mike Schuchardt837d5162018-03-08 12:57:02 -0700565 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
Jeremy Kniager979b5312019-11-22 14:55:57 -0700566 __android_log_print(ANDROID_LOG_WARN, APP_SHORT_NAME, "%s", message);
Mike Schuchardt837d5162018-03-08 12:57:02 -0700567 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
Cody Northropaf28a532016-09-27 10:50:57 -0600568 __android_log_print(ANDROID_LOG_ERROR, APP_SHORT_NAME, "%s", message);
Mike Schuchardt837d5162018-03-08 12:57:02 -0700569 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
570 __android_log_print(ANDROID_LOG_VERBOSE, APP_SHORT_NAME, "%s", message);
Cody Northropc5e5a8c2016-09-26 21:05:00 -0600571 } else {
Jeremy Kniager979b5312019-11-22 14:55:57 -0700572 __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
Cody Northropc5e5a8c2016-09-26 21:05:00 -0600573 }
Cody Northropaf28a532016-09-27 10:50:57 -0600574
lenny-lunargfbe22392016-06-06 11:07:53 -0600575#else
Cody Northropaf28a532016-09-27 10:50:57 -0600576
lenny-lunargfbe22392016-06-06 11:07:53 -0600577 printf("%s\n", message);
578 fflush(stdout);
Cody Northropaf28a532016-09-27 10:50:57 -0600579
lenny-lunargfbe22392016-06-06 11:07:53 -0600580#endif
Cody Northropaf28a532016-09-27 10:50:57 -0600581
lenny-lunargfbe22392016-06-06 11:07:53 -0600582 free(message);
583
Mark Young66510e52017-11-10 10:05:14 -0700584 // Don't bail out, but keep going.
lenny-lunargfbe22392016-06-06 11:07:53 -0600585 return false;
586}
587
Ian Elliottd940ca22017-03-22 08:31:27 -0600588bool ActualTimeLate(uint64_t desired, uint64_t actual, uint64_t rdur) {
589 // The desired time was the earliest time that the present should have
590 // occured. In almost every case, the actual time should be later than the
591 // desired time. We should only consider the actual time "late" if it is
592 // after "desired + rdur".
593 if (actual <= desired) {
594 // The actual time was before or equal to the desired time. This will
595 // probably never happen, but in case it does, return false since the
596 // present was obviously NOT late.
597 return false;
598 }
Liam Middlebrook881fe392018-05-03 15:52:32 -0700599 uint64_t deadline = desired + rdur;
Ian Elliottd940ca22017-03-22 08:31:27 -0600600 if (actual > deadline) {
601 return true;
602 } else {
603 return false;
604 }
605}
Dave Houlton5fa47912018-02-16 11:02:26 -0700606bool CanPresentEarlier(uint64_t earliest, uint64_t actual, uint64_t margin, uint64_t rdur) {
Ian Elliottd940ca22017-03-22 08:31:27 -0600607 if (earliest < actual) {
608 // Consider whether this present could have occured earlier. Make sure
609 // that earliest time was at least 2msec earlier than actual time, and
610 // that the margin was at least 2msec:
611 uint64_t diff = actual - earliest;
612 if ((diff >= (2 * MILLION)) && (margin >= (2 * MILLION))) {
613 // This present could have occured earlier because both: 1) the
614 // earliest time was at least 2 msec before actual time, and 2) the
615 // margin was at least 2msec.
616 return true;
617 }
618 }
619 return false;
620}
621
Tony-LunarG6cebf142019-09-11 14:32:23 -0600622// Forward declarations:
Ian Elliottcf074d32015-10-16 18:02:43 -0600623static void demo_resize(struct demo *demo);
Tony-LunarG6cebf142019-09-11 14:32:23 -0600624static void demo_create_surface(struct demo *demo);
Ian Elliottcf074d32015-10-16 18:02:43 -0600625
Dave Houlton5fa47912018-02-16 11:02:26 -0700626static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
Karl Schultze4dc75c2016-02-02 15:37:51 -0700627 // Search memtypes to find first index with those properties
Alexandre BACQUART89eb8df2016-04-28 14:25:09 -0600628 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
Karl Schultze4dc75c2016-02-02 15:37:51 -0700629 if ((typeBits & 1) == 1) {
630 // Type is available, does it match user properties?
Dave Houlton5fa47912018-02-16 11:02:26 -0700631 if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
Karl Schultze4dc75c2016-02-02 15:37:51 -0700632 *typeIndex = i;
633 return true;
634 }
635 }
636 typeBits >>= 1;
637 }
638 // No memory types matched, return failure
639 return false;
Mark Lobodzinskieadf9982015-07-02 16:49:40 -0600640}
641
Karl Schultze4dc75c2016-02-02 15:37:51 -0700642static void demo_flush_init_cmd(struct demo *demo) {
Tony Barbourfdc2d352015-04-22 09:02:32 -0600643 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600644
Tony Barbource7524e2016-07-28 12:01:45 -0600645 // This function could get called twice if the texture uses a staging buffer
646 // In that case the second call should be ignored
Dave Houlton5fa47912018-02-16 11:02:26 -0700647 if (demo->cmd == VK_NULL_HANDLE) return;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600648
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600649 err = vkEndCommandBuffer(demo->cmd);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600650 assert(!err);
651
Tony Barbource7524e2016-07-28 12:01:45 -0600652 VkFence fence;
Dave Houlton5fa47912018-02-16 11:02:26 -0700653 VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0};
Mark Young43c08f82021-11-30 16:38:25 -0700654 if (demo->force_errors) {
655 // Remove sType to intentionally force validation layer errors.
656 fence_ci.sType = 0;
657 }
Tony Barboura72d9492017-01-11 13:35:09 -0700658 err = vkCreateFence(demo->device, &fence_ci, NULL, &fence);
659 assert(!err);
660
Karl Schultze4dc75c2016-02-02 15:37:51 -0700661 const VkCommandBuffer cmd_bufs[] = {demo->cmd};
Karl Schultze4dc75c2016-02-02 15:37:51 -0700662 VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
663 .pNext = NULL,
664 .waitSemaphoreCount = 0,
665 .pWaitSemaphores = NULL,
666 .pWaitDstStageMask = NULL,
667 .commandBufferCount = 1,
668 .pCommandBuffers = cmd_bufs,
669 .signalSemaphoreCount = 0,
670 .pSignalSemaphores = NULL};
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600671
Tony Barbource7524e2016-07-28 12:01:45 -0600672 err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600673 assert(!err);
674
Tony Barbource7524e2016-07-28 12:01:45 -0600675 err = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600676 assert(!err);
677
Courtney Goeltzenleuchter014ded82015-10-23 14:21:05 -0600678 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
Tony Barbource7524e2016-07-28 12:01:45 -0600679 vkDestroyFence(demo->device, fence, NULL);
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600680 demo->cmd = VK_NULL_HANDLE;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600681}
682
Dave Houlton5fa47912018-02-16 11:02:26 -0700683static void demo_set_image_layout(struct demo *demo, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout,
684 VkImageLayout new_image_layout, VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages,
Tony Barbour5ff13182016-10-19 13:58:29 -0600685 VkPipelineStageFlags dest_stages) {
Tony Barbour6db4fcb2016-10-19 13:41:16 -0600686 assert(demo->cmd);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600687
Dave Houlton5fa47912018-02-16 11:02:26 -0700688 VkImageMemoryBarrier image_memory_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
689 .pNext = NULL,
690 .srcAccessMask = srcAccessMask,
691 .dstAccessMask = 0,
Tony-LunarGa141b962018-05-30 11:33:19 -0600692 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
693 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
Dave Houlton5fa47912018-02-16 11:02:26 -0700694 .oldLayout = old_image_layout,
695 .newLayout = new_image_layout,
696 .image = image,
697 .subresourceRange = {aspectMask, 0, 1, 0, 1}};
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600698
Tony Barboureb5077b2016-10-19 15:23:36 -0600699 switch (new_image_layout) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700700 case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
701 /* Make sure anything that was copying from this image has completed */
702 image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
703 break;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600704
Dave Houlton5fa47912018-02-16 11:02:26 -0700705 case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
706 image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
707 break;
Mark Lobodzinski9e0be702015-11-04 13:49:48 -0700708
Dave Houlton5fa47912018-02-16 11:02:26 -0700709 case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
710 image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
711 break;
Mark Lobodzinski9e0be702015-11-04 13:49:48 -0700712
Dave Houlton5fa47912018-02-16 11:02:26 -0700713 case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
714 image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
715 break;
Tony Barboureb5077b2016-10-19 15:23:36 -0600716
Dave Houlton5fa47912018-02-16 11:02:26 -0700717 case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
718 image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
719 break;
Tony Barboureb5077b2016-10-19 15:23:36 -0600720
Dave Houlton5fa47912018-02-16 11:02:26 -0700721 case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
722 image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
723 break;
Tony Barboureb5077b2016-10-19 15:23:36 -0600724
Dave Houlton5fa47912018-02-16 11:02:26 -0700725 default:
726 image_memory_barrier.dstAccessMask = 0;
727 break;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600728 }
729
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600730 VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600731
Dave Houlton5fa47912018-02-16 11:02:26 -0700732 vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600733}
734
Karl Schultze4dc75c2016-02-02 15:37:51 -0700735static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) {
Lenny Komowe830b592018-02-23 16:18:36 -0700736 VkDebugUtilsLabelEXT label;
737 memset(&label, 0, sizeof(label));
Jon Ashburn0bec67e2016-01-11 13:12:43 -0700738 const VkCommandBufferBeginInfo cmd_buf_info = {
739 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
740 .pNext = NULL,
Tony Barbource7524e2016-07-28 12:01:45 -0600741 .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
Rene Lindsayd787e3a2016-07-07 16:00:14 -0700742 .pInheritanceInfo = NULL,
Jon Ashburn0bec67e2016-01-11 13:12:43 -0700743 };
Chia-I Wua74c5b22015-07-07 11:50:03 +0800744 const VkClearValue clear_values[2] = {
Dave Houlton5fa47912018-02-16 11:02:26 -0700745 [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
746 [1] = {.depthStencil = {1.0f, 0}},
Chia-I Wua74c5b22015-07-07 11:50:03 +0800747 };
748 const VkRenderPassBeginInfo rp_begin = {
749 .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
750 .pNext = NULL,
Chia-I Wuf973e322015-07-08 13:34:24 +0800751 .renderPass = demo->render_pass,
Tony Barboura72d9492017-01-11 13:35:09 -0700752 .framebuffer = demo->swapchain_image_resources[demo->current_buffer].framebuffer,
Chia-I Wua74c5b22015-07-07 11:50:03 +0800753 .renderArea.offset.x = 0,
754 .renderArea.offset.y = 0,
755 .renderArea.extent.width = demo->width,
756 .renderArea.extent.height = demo->height,
Cody Northrop372bbae2015-08-04 11:51:03 -0600757 .clearValueCount = 2,
758 .pClearValues = clear_values,
Jon Ashburn08f6eb92015-01-02 18:24:05 -0700759 };
Chia-I Wuf973e322015-07-08 13:34:24 +0800760 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600761
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600762 err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info);
Mark Young66510e52017-11-10 10:05:14 -0700763
764 if (demo->validate) {
765 // Set a name for the command buffer
766 VkDebugUtilsObjectNameInfoEXT cmd_buf_name = {
767 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
768 .pNext = NULL,
769 .objectType = VK_OBJECT_TYPE_COMMAND_BUFFER,
770 .objectHandle = (uint64_t)cmd_buf,
771 .pObjectName = "CubeDrawCommandBuf",
772 };
773 demo->SetDebugUtilsObjectNameEXT(demo->device, &cmd_buf_name);
774
775 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
776 label.pNext = NULL;
777 label.pLabelName = "DrawBegin";
778 label.color[0] = 0.4f;
779 label.color[1] = 0.3f;
780 label.color[2] = 0.2f;
781 label.color[3] = 0.1f;
782 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
783 }
784
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600785 assert(!err);
Chia-I Wuf051d262015-10-27 19:25:11 +0800786 vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
Mark Young66510e52017-11-10 10:05:14 -0700787
788 if (demo->validate) {
789 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
790 label.pNext = NULL;
791 label.pLabelName = "InsideRenderPass";
792 label.color[0] = 8.4f;
793 label.color[1] = 7.3f;
794 label.color[2] = 6.2f;
795 label.color[3] = 7.1f;
796 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
797 }
798
Karl Schultze4dc75c2016-02-02 15:37:51 -0700799 vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
Dave Houlton5fa47912018-02-16 11:02:26 -0700800 vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1,
801 &demo->swapchain_image_resources[demo->current_buffer].descriptor_set, 0, NULL);
Courtney Goeltzenleuchter4cbf78b2015-09-17 15:06:17 -0600802 VkViewport viewport;
803 memset(&viewport, 0, sizeof(viewport));
Jeremy Kniager979b5312019-11-22 14:55:57 -0700804 float viewport_dimension;
805 if (demo->width < demo->height) {
806 viewport_dimension = (float)demo->width;
807 viewport.y = (demo->height - demo->width) / 2.0f;
808 } else {
809 viewport_dimension = (float)demo->height;
810 viewport.x = (demo->width - demo->height) / 2.0f;
811 }
812 viewport.height = viewport_dimension;
813 viewport.width = viewport_dimension;
Karl Schultze4dc75c2016-02-02 15:37:51 -0700814 viewport.minDepth = (float)0.0f;
815 viewport.maxDepth = (float)1.0f;
Jon Ashburn19255f82015-12-30 14:06:55 -0700816 vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
Courtney Goeltzenleuchter4cbf78b2015-09-17 15:06:17 -0600817
818 VkRect2D scissor;
819 memset(&scissor, 0, sizeof(scissor));
820 scissor.extent.width = demo->width;
821 scissor.extent.height = demo->height;
822 scissor.offset.x = 0;
823 scissor.offset.y = 0;
Jon Ashburn19255f82015-12-30 14:06:55 -0700824 vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
Mark Young66510e52017-11-10 10:05:14 -0700825
826 if (demo->validate) {
827 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
828 label.pNext = NULL;
829 label.pLabelName = "ActualDraw";
Mike Schuchardt4cf3aa42018-02-23 12:44:05 -0700830 label.color[0] = -0.4f;
831 label.color[1] = -0.3f;
832 label.color[2] = -0.2f;
833 label.color[3] = -0.1f;
Mark Young66510e52017-11-10 10:05:14 -0700834 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
835 }
836
Courtney Goeltzenleuchter332a3672015-09-23 12:31:50 -0600837 vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
Mark Young66510e52017-11-10 10:05:14 -0700838 if (demo->validate) {
839 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
840 }
841
Tony Barbour98390392016-07-28 10:50:13 -0600842 // Note that ending the renderpass changes the image's layout from
Tony Barbour22e06272016-09-07 16:07:56 -0600843 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
Chia-I Wu57b23b42015-06-26 15:34:39 +0800844 vkCmdEndRenderPass(cmd_buf);
Mark Young66510e52017-11-10 10:05:14 -0700845 if (demo->validate) {
846 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
847 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600848
Tony Barbour22e06272016-09-07 16:07:56 -0600849 if (demo->separate_present_queue) {
850 // We have to transfer ownership from the graphics queue family to the
851 // present queue family to be able to present. Note that we don't have
852 // to transfer from present queue family back to graphics queue family at
853 // the start of the next frame because we don't care about the image's
854 // contents at that point.
Dave Houlton5fa47912018-02-16 11:02:26 -0700855 VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
856 .pNext = NULL,
857 .srcAccessMask = 0,
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600858 .dstAccessMask = 0,
Dave Houlton5fa47912018-02-16 11:02:26 -0700859 .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
860 .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
861 .srcQueueFamilyIndex = demo->graphics_queue_family_index,
862 .dstQueueFamilyIndex = demo->present_queue_family_index,
863 .image = demo->swapchain_image_resources[demo->current_buffer].image,
864 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
Tony Barbour22e06272016-09-07 16:07:56 -0600865
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600866 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
867 NULL, 1, &image_ownership_barrier);
Tony Barbour22e06272016-09-07 16:07:56 -0600868 }
Mark Young66510e52017-11-10 10:05:14 -0700869 if (demo->validate) {
870 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
871 }
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600872 err = vkEndCommandBuffer(cmd_buf);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600873 assert(!err);
874}
875
Tony Barbour22e06272016-09-07 16:07:56 -0600876void demo_build_image_ownership_cmd(struct demo *demo, int i) {
877 VkResult U_ASSERT_ONLY err;
878
879 const VkCommandBufferBeginInfo cmd_buf_info = {
880 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
881 .pNext = NULL,
882 .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
883 .pInheritanceInfo = NULL,
884 };
Dave Houlton5fa47912018-02-16 11:02:26 -0700885 err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
Tony Barbour22e06272016-09-07 16:07:56 -0600886 assert(!err);
887
Dave Houlton5fa47912018-02-16 11:02:26 -0700888 VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
889 .pNext = NULL,
890 .srcAccessMask = 0,
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600891 .dstAccessMask = 0,
Dave Houlton5fa47912018-02-16 11:02:26 -0700892 .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
893 .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
894 .srcQueueFamilyIndex = demo->graphics_queue_family_index,
895 .dstQueueFamilyIndex = demo->present_queue_family_index,
896 .image = demo->swapchain_image_resources[i].image,
897 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
Tony Barbour22e06272016-09-07 16:07:56 -0600898
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600899 vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
900 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &image_ownership_barrier);
Tony Barboura72d9492017-01-11 13:35:09 -0700901 err = vkEndCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd);
Tony Barbour22e06272016-09-07 16:07:56 -0600902 assert(!err);
903}
904
Karl Schultze4dc75c2016-02-02 15:37:51 -0700905void demo_update_data_buffer(struct demo *demo) {
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600906 mat4x4 MVP, Model, VP;
907 int matrixSize = sizeof(MVP);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600908
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600909 mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600910
Karl Schultz6ddf1e02017-01-04 10:31:20 -0700911 // Rotate around the Y axis
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600912 mat4x4_dup(Model, demo->model_matrix);
Arman Uguray3ae08892021-05-25 00:07:24 -0700913 mat4x4_rotate_Y(demo->model_matrix, Model, (float)degreesToRadians(demo->spin_angle));
914 mat4x4_orthonormalize(demo->model_matrix, demo->model_matrix);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600915 mat4x4_mul(MVP, VP, demo->model_matrix);
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600916
Tony-LunarG37af49f2019-12-19 12:04:19 -0700917 memcpy(demo->swapchain_image_resources[demo->current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], matrixSize);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600918}
919
Ian Elliottd940ca22017-03-22 08:31:27 -0600920void DemoUpdateTargetIPD(struct demo *demo) {
921 // Look at what happened to previous presents, and make appropriate
922 // adjustments in timing:
923 VkResult U_ASSERT_ONLY err;
Dave Houlton5fa47912018-02-16 11:02:26 -0700924 VkPastPresentationTimingGOOGLE *past = NULL;
Ian Elliottd940ca22017-03-22 08:31:27 -0600925 uint32_t count = 0;
Ian Elliottd940ca22017-03-22 08:31:27 -0600926
Dave Houlton5fa47912018-02-16 11:02:26 -0700927 err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, NULL);
Ian Elliottd940ca22017-03-22 08:31:27 -0600928 assert(!err);
Ian Elliottd940ca22017-03-22 08:31:27 -0600929 if (count) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700930 past = (VkPastPresentationTimingGOOGLE *)malloc(sizeof(VkPastPresentationTimingGOOGLE) * count);
Ian Elliottd940ca22017-03-22 08:31:27 -0600931 assert(past);
Dave Houlton5fa47912018-02-16 11:02:26 -0700932 err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, past);
Ian Elliottd940ca22017-03-22 08:31:27 -0600933 assert(!err);
934
935 bool early = false;
936 bool late = false;
937 bool calibrate_next = false;
Dave Houlton5fa47912018-02-16 11:02:26 -0700938 for (uint32_t i = 0; i < count; i++) {
Ian Elliottd940ca22017-03-22 08:31:27 -0600939 if (!demo->syncd_with_actual_presents) {
940 // This is the first time that we've received an
941 // actualPresentTime for this swapchain. In order to not
942 // perceive these early frames as "late", we need to sync-up
943 // our future desiredPresentTime's with the
944 // actualPresentTime(s) that we're receiving now.
945 calibrate_next = true;
Ian Elliottd940ca22017-03-22 08:31:27 -0600946
Ian Elliottd940ca22017-03-22 08:31:27 -0600947 // So that we don't suspect any pending presents as late,
948 // record them all as suspected-late presents:
949 demo->last_late_id = demo->next_present_id - 1;
950 demo->last_early_id = 0;
Ian Elliottd940ca22017-03-22 08:31:27 -0600951 demo->syncd_with_actual_presents = true;
952 break;
Dave Houlton5fa47912018-02-16 11:02:26 -0700953 } else if (CanPresentEarlier(past[i].earliestPresentTime, past[i].actualPresentTime, past[i].presentMargin,
Ian Elliottd940ca22017-03-22 08:31:27 -0600954 demo->refresh_duration)) {
955 // This image could have been presented earlier. We don't want
956 // to decrease the target_IPD until we've seen early presents
957 // for at least two seconds.
958 if (demo->last_early_id == past[i].presentID) {
959 // We've now seen two seconds worth of early presents.
960 // Flag it as such, and reset the counter:
961 early = true;
962 demo->last_early_id = 0;
963 } else if (demo->last_early_id == 0) {
964 // This is the first early present we've seen.
965 // Calculate the presentID for two seconds from now.
Dave Houlton5fa47912018-02-16 11:02:26 -0700966 uint64_t lastEarlyTime = past[i].actualPresentTime + (2 * BILLION);
967 uint32_t howManyPresents = (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD);
Ian Elliottd940ca22017-03-22 08:31:27 -0600968 demo->last_early_id = past[i].presentID + howManyPresents;
969 } else {
970 // We are in the midst of a set of early images,
971 // and so we won't do anything.
972 }
973 late = false;
974 demo->last_late_id = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -0700975 } else if (ActualTimeLate(past[i].desiredPresentTime, past[i].actualPresentTime, demo->refresh_duration)) {
Ian Elliottd940ca22017-03-22 08:31:27 -0600976 // This image was presented after its desired time. Since
977 // there's a delay between calling vkQueuePresentKHR and when
978 // we get the timing data, several presents may have been late.
979 // Thus, we need to threat all of the outstanding presents as
980 // being likely late, so that we only increase the target_IPD
981 // once for all of those presents.
Dave Houlton5fa47912018-02-16 11:02:26 -0700982 if ((demo->last_late_id == 0) || (demo->last_late_id < past[i].presentID)) {
Ian Elliottd940ca22017-03-22 08:31:27 -0600983 late = true;
984 // Record the last suspected-late present:
985 demo->last_late_id = demo->next_present_id - 1;
986 } else {
987 // We are in the midst of a set of likely-late images,
988 // and so we won't do anything.
989 }
990 early = false;
991 demo->last_early_id = 0;
992 } else {
993 // Since this image was not presented early or late, reset
994 // any sets of early or late presentIDs:
995 early = false;
996 late = false;
997 calibrate_next = true;
998 demo->last_early_id = 0;
999 demo->last_late_id = 0;
1000 }
1001 }
1002
1003 if (early) {
1004 // Since we've seen at least two-seconds worth of presnts that
1005 // could have occured earlier than desired, let's decrease the
1006 // target_IPD (i.e. increase the frame rate):
1007 //
1008 // TODO(ianelliott): Try to calculate a better target_IPD based
1009 // on the most recently-seen present (this is overly-simplistic).
1010 demo->refresh_duration_multiplier--;
1011 if (demo->refresh_duration_multiplier == 0) {
1012 // This should never happen, but in case it does, don't
1013 // try to go faster.
1014 demo->refresh_duration_multiplier = 1;
1015 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001016 demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
Ian Elliottd940ca22017-03-22 08:31:27 -06001017 }
1018 if (late) {
1019 // Since we found a new instance of a late present, we want to
1020 // increase the target_IPD (i.e. decrease the frame rate):
1021 //
1022 // TODO(ianelliott): Try to calculate a better target_IPD based
1023 // on the most recently-seen present (this is overly-simplistic).
1024 demo->refresh_duration_multiplier++;
Dave Houlton5fa47912018-02-16 11:02:26 -07001025 demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
Ian Elliottd940ca22017-03-22 08:31:27 -06001026 }
1027
1028 if (calibrate_next) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001029 int64_t multiple = demo->next_present_id - past[count - 1].presentID;
1030 demo->prev_desired_present_time = (past[count - 1].actualPresentTime + (multiple * demo->target_IPD));
Ian Elliottd940ca22017-03-22 08:31:27 -06001031 }
Karl Schultza33771f2018-05-28 16:16:47 -06001032 free(past);
Ian Elliottd940ca22017-03-22 08:31:27 -06001033 }
Ian Elliottd940ca22017-03-22 08:31:27 -06001034}
1035
Karl Schultze4dc75c2016-02-02 15:37:51 -07001036static void demo_draw(struct demo *demo) {
Tony Barbourfdc2d352015-04-22 09:02:32 -06001037 VkResult U_ASSERT_ONLY err;
Tony Barboure35e8aa2016-06-20 10:44:08 -06001038
Damien Leonec336d822017-04-14 16:10:14 -07001039 // Ensure no more than FRAME_LAG renderings are outstanding
szdarkhackd322ff02016-10-08 09:51:22 +03001040 vkWaitForFences(demo->device, 1, &demo->fences[demo->frame_index], VK_TRUE, UINT64_MAX);
1041 vkResetFences(demo->device, 1, &demo->fences[demo->frame_index]);
Tony Barbour66a56c32016-09-21 13:10:56 -06001042
Tony Barbour8b7c9112017-06-29 13:34:41 -06001043 do {
Tony Barbour6914e6d2017-06-02 12:11:29 -06001044 // Get the index of the next available swapchain image:
Dave Houlton5fa47912018-02-16 11:02:26 -07001045 err =
1046 demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX,
1047 demo->image_acquired_semaphores[demo->frame_index], VK_NULL_HANDLE, &demo->current_buffer);
Tony Barbour66a56c32016-09-21 13:10:56 -06001048
Tony Barbour6914e6d2017-06-02 12:11:29 -06001049 if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1050 // demo->swapchain is out of date (e.g. the window was resized) and
1051 // must be recreated:
1052 demo_resize(demo);
1053 } else if (err == VK_SUBOPTIMAL_KHR) {
1054 // demo->swapchain is not as optimal as it could be, but the platform's
1055 // presentation engine will still present the image correctly.
1056 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -06001057 } else if (err == VK_ERROR_SURFACE_LOST_KHR) {
1058 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
1059 demo_create_surface(demo);
1060 demo_resize(demo);
Tony Barbour6914e6d2017-06-02 12:11:29 -06001061 } else {
1062 assert(!err);
1063 }
Tony Barbour8b7c9112017-06-29 13:34:41 -06001064 } while (err != VK_SUCCESS);
Tony Barbour6914e6d2017-06-02 12:11:29 -06001065
Tony Barbour3eafe1f2017-06-14 11:59:55 -06001066 demo_update_data_buffer(demo);
1067
Ian Elliottd940ca22017-03-22 08:31:27 -06001068 if (demo->VK_GOOGLE_display_timing_enabled) {
1069 // Look at what happened to previous presents, and make appropriate
1070 // adjustments in timing:
1071 DemoUpdateTargetIPD(demo);
1072
1073 // Note: a real application would position its geometry to that it's in
1074 // the correct locatoin for when the next image is presented. It might
1075 // also wait, so that there's less latency between any input and when
1076 // the next image is rendered/presented. This demo program is so
1077 // simple that it doesn't do either of those.
1078 }
1079
Tony Barbource7524e2016-07-28 12:01:45 -06001080 // Wait for the image acquired semaphore to be signaled to ensure
Courtney Goeltzenleuchter5fa898d2015-10-20 18:04:07 -06001081 // that the image won't be rendered to until the presentation
1082 // engine has fully released ownership to the application, and it is
1083 // okay to render to the image.
Tony Barbour22e06272016-09-07 16:07:56 -06001084 VkPipelineStageFlags pipe_stage_flags;
1085 VkSubmitInfo submit_info;
1086 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1087 submit_info.pNext = NULL;
Tony Barbour22e06272016-09-07 16:07:56 -06001088 pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
Eleni Maria Steae8b24f02021-10-02 23:32:06 +03001089 submit_info.pWaitDstStageMask = &pipe_stage_flags;
Tony Barbour22e06272016-09-07 16:07:56 -06001090 submit_info.waitSemaphoreCount = 1;
Tony Barbour66a56c32016-09-21 13:10:56 -06001091 submit_info.pWaitSemaphores = &demo->image_acquired_semaphores[demo->frame_index];
Tony Barbour22e06272016-09-07 16:07:56 -06001092 submit_info.commandBufferCount = 1;
Tony Barboura72d9492017-01-11 13:35:09 -07001093 submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].cmd;
Tony Barbour22e06272016-09-07 16:07:56 -06001094 submit_info.signalSemaphoreCount = 1;
Tony Barbour66a56c32016-09-21 13:10:56 -06001095 submit_info.pSignalSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
Dave Houlton5fa47912018-02-16 11:02:26 -07001096 err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, demo->fences[demo->frame_index]);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001097 assert(!err);
1098
Tony Barbour22e06272016-09-07 16:07:56 -06001099 if (demo->separate_present_queue) {
1100 // If we are using separate queues, change image ownership to the
1101 // present queue before presenting, waiting for the draw complete
1102 // semaphore and signalling the ownership released semaphore when finished
Tony Barboura72d9492017-01-11 13:35:09 -07001103 VkFence nullFence = VK_NULL_HANDLE;
Tony Barbour22e06272016-09-07 16:07:56 -06001104 pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1105 submit_info.waitSemaphoreCount = 1;
Tony Barbour66a56c32016-09-21 13:10:56 -06001106 submit_info.pWaitSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
Tony Barbour22e06272016-09-07 16:07:56 -06001107 submit_info.commandBufferCount = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07001108 submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd;
Tony Barbour22e06272016-09-07 16:07:56 -06001109 submit_info.signalSemaphoreCount = 1;
Tony Barbour66a56c32016-09-21 13:10:56 -06001110 submit_info.pSignalSemaphores = &demo->image_ownership_semaphores[demo->frame_index];
Tony Barbour22e06272016-09-07 16:07:56 -06001111 err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence);
1112 assert(!err);
1113 }
1114
1115 // If we are using separate queues we have to wait for image ownership,
1116 // otherwise wait for draw complete
Ian Elliotta0781972015-08-21 15:09:33 -06001117 VkPresentInfoKHR present = {
1118 .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
Ian Elliottaaae5352015-07-06 14:27:58 -06001119 .pNext = NULL,
Ian Elliottcf7f7482016-08-19 03:46:58 -06001120 .waitSemaphoreCount = 1,
Dave Houlton5fa47912018-02-16 11:02:26 -07001121 .pWaitSemaphores = (demo->separate_present_queue) ? &demo->image_ownership_semaphores[demo->frame_index]
1122 : &demo->draw_complete_semaphores[demo->frame_index],
Ian Elliotta0781972015-08-21 15:09:33 -06001123 .swapchainCount = 1,
Ian Elliottb08e0d92015-11-20 11:55:46 -07001124 .pSwapchains = &demo->swapchain,
1125 .pImageIndices = &demo->current_buffer,
Ian Elliottaaae5352015-07-06 14:27:58 -06001126 };
1127
Dave Airlie48a68f92019-04-12 17:04:48 +10001128 VkRectLayerKHR rect;
1129 VkPresentRegionKHR region;
1130 VkPresentRegionsKHR regions;
Ian Elliott53622a72017-03-28 11:06:33 -06001131 if (demo->VK_KHR_incremental_present_enabled) {
1132 // If using VK_KHR_incremental_present, we provide a hint of the region
1133 // that contains changed content relative to the previously-presented
1134 // image. The implementation can use this hint in order to save
1135 // work/power (by only copying the region in the hint). The
1136 // implementation is free to ignore the hint though, and so we must
1137 // ensure that the entire image has the correctly-drawn content.
1138 uint32_t eighthOfWidth = demo->width / 8;
1139 uint32_t eighthOfHeight = demo->height / 8;
Dave Airlie48a68f92019-04-12 17:04:48 +10001140
1141 rect.offset.x = eighthOfWidth;
1142 rect.offset.y = eighthOfHeight;
1143 rect.extent.width = eighthOfWidth * 6;
1144 rect.extent.height = eighthOfHeight * 6;
1145 rect.layer = 0;
1146
1147 region.rectangleCount = 1;
1148 region.pRectangles = &rect;
1149
1150 regions.sType = VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR;
1151 regions.pNext = present.pNext;
1152 regions.swapchainCount = present.swapchainCount;
1153 regions.pRegions = &region;
Ian Elliott53622a72017-03-28 11:06:33 -06001154 present.pNext = &regions;
Ian Elliott53622a72017-03-28 11:06:33 -06001155 }
1156
Ian Elliottd940ca22017-03-22 08:31:27 -06001157 if (demo->VK_GOOGLE_display_timing_enabled) {
1158 VkPresentTimeGOOGLE ptime;
1159 if (demo->prev_desired_present_time == 0) {
1160 // This must be the first present for this swapchain.
1161 //
1162 // We don't know where we are relative to the presentation engine's
1163 // display's refresh cycle. We also don't know how long rendering
1164 // takes. Let's make a grossly-simplified assumption that the
1165 // desiredPresentTime should be half way between now and
1166 // now+target_IPD. We will adjust over time.
1167 uint64_t curtime = getTimeInNanoseconds();
1168 if (curtime == 0) {
1169 // Since we didn't find out the current time, don't give a
1170 // desiredPresentTime:
1171 ptime.desiredPresentTime = 0;
1172 } else {
Ian Elliottd940ca22017-03-22 08:31:27 -06001173 ptime.desiredPresentTime = curtime + (demo->target_IPD >> 1);
1174 }
1175 } else {
Dave Houlton5fa47912018-02-16 11:02:26 -07001176 ptime.desiredPresentTime = (demo->prev_desired_present_time + demo->target_IPD);
Ian Elliottd940ca22017-03-22 08:31:27 -06001177 }
1178 ptime.presentID = demo->next_present_id++;
1179 demo->prev_desired_present_time = ptime.desiredPresentTime;
Ian Elliottd940ca22017-03-22 08:31:27 -06001180
1181 VkPresentTimesInfoGOOGLE present_time = {
1182 .sType = VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,
1183 .pNext = present.pNext,
1184 .swapchainCount = present.swapchainCount,
1185 .pTimes = &ptime,
1186 };
1187 if (demo->VK_GOOGLE_display_timing_enabled) {
1188 present.pNext = &present_time;
Ian Elliottd940ca22017-03-22 08:31:27 -06001189 }
1190 }
1191
Tony Barboura2a67812016-07-18 13:21:06 -06001192 err = demo->fpQueuePresentKHR(demo->present_queue, &present);
Tony Barbour66a56c32016-09-21 13:10:56 -06001193 demo->frame_index += 1;
1194 demo->frame_index %= FRAME_LAG;
1195
Ian Elliottcf074d32015-10-16 18:02:43 -06001196 if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1197 // demo->swapchain is out of date (e.g. the window was resized) and
1198 // must be recreated:
1199 demo_resize(demo);
1200 } else if (err == VK_SUBOPTIMAL_KHR) {
Tony-LunarGa8e96342021-06-04 15:12:55 -06001201 // SUBOPTIMAL could be due to a resize
1202 VkSurfaceCapabilitiesKHR surfCapabilities;
1203 err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
1204 assert(!err);
Tony-LunarGbbdf5842021-06-11 12:00:30 -06001205 if (surfCapabilities.currentExtent.width != (uint32_t)demo->width ||
1206 surfCapabilities.currentExtent.height != (uint32_t)demo->height) {
Tony-LunarGa8e96342021-06-04 15:12:55 -06001207 demo_resize(demo);
1208 }
Tony-LunarG6cebf142019-09-11 14:32:23 -06001209 } else if (err == VK_ERROR_SURFACE_LOST_KHR) {
1210 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
1211 demo_create_surface(demo);
1212 demo_resize(demo);
Ian Elliottcf074d32015-10-16 18:02:43 -06001213 } else {
1214 assert(!err);
1215 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001216}
1217
Karl Schultze4dc75c2016-02-02 15:37:51 -07001218static void demo_prepare_buffers(struct demo *demo) {
Ian Elliottaaae5352015-07-06 14:27:58 -06001219 VkResult U_ASSERT_ONLY err;
Ian Elliottcf074d32015-10-16 18:02:43 -06001220 VkSwapchainKHR oldSwapchain = demo->swapchain;
Ian Elliottaaae5352015-07-06 14:27:58 -06001221
Ian Elliottb08e0d92015-11-20 11:55:46 -07001222 // Check the surface capabilities and formats
1223 VkSurfaceCapabilitiesKHR surfCapabilities;
Dave Houlton5fa47912018-02-16 11:02:26 -07001224 err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
Ian Elliottaaae5352015-07-06 14:27:58 -06001225 assert(!err);
1226
Ian Elliott8528eff2015-08-07 15:56:59 -06001227 uint32_t presentModeCount;
Dave Houlton5fa47912018-02-16 11:02:26 -07001228 err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, NULL);
Ian Elliottaaae5352015-07-06 14:27:58 -06001229 assert(!err);
Dave Houlton5fa47912018-02-16 11:02:26 -07001230 VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
Ian Elliott8528eff2015-08-07 15:56:59 -06001231 assert(presentModes);
Dave Houlton5fa47912018-02-16 11:02:26 -07001232 err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, presentModes);
Ian Elliottaaae5352015-07-06 14:27:58 -06001233 assert(!err);
1234
Ian Elliotta0781972015-08-21 15:09:33 -06001235 VkExtent2D swapchainExtent;
Ian Elliottcf7f7482016-08-19 03:46:58 -06001236 // width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
1237 if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
1238 // If the surface size is undefined, the size is set to the size
1239 // of the images requested, which must fit within the minimum and
1240 // maximum values.
Ian Elliotta0781972015-08-21 15:09:33 -06001241 swapchainExtent.width = demo->width;
1242 swapchainExtent.height = demo->height;
Ian Elliottcf7f7482016-08-19 03:46:58 -06001243
1244 if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
1245 swapchainExtent.width = surfCapabilities.minImageExtent.width;
1246 } else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
1247 swapchainExtent.width = surfCapabilities.maxImageExtent.width;
1248 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001249
Ian Elliottcf7f7482016-08-19 03:46:58 -06001250 if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
1251 swapchainExtent.height = surfCapabilities.minImageExtent.height;
1252 } else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
1253 swapchainExtent.height = surfCapabilities.maxImageExtent.height;
1254 }
Karl Schultze4dc75c2016-02-02 15:37:51 -07001255 } else {
Ian Elliottaaae5352015-07-06 14:27:58 -06001256 // If the surface size is defined, the swap chain size must match
Ian Elliottb08e0d92015-11-20 11:55:46 -07001257 swapchainExtent = surfCapabilities.currentExtent;
1258 demo->width = surfCapabilities.currentExtent.width;
1259 demo->height = surfCapabilities.currentExtent.height;
Ian Elliottaaae5352015-07-06 14:27:58 -06001260 }
1261
Joshua Ashtona6806712021-06-17 18:30:14 +01001262 if (surfCapabilities.maxImageExtent.width == 0 || surfCapabilities.maxImageExtent.height == 0) {
Jeremy Kniager602e4182018-01-19 10:52:34 -07001263 demo->is_minimized = true;
1264 return;
1265 } else {
1266 demo->is_minimized = false;
1267 }
1268
Tony Barbour66a56c32016-09-21 13:10:56 -06001269 // The FIFO present mode is guaranteed by the spec to be supported
Ian Elliottb18fdde2016-10-03 12:11:12 -06001270 // and to have no tearing. It's a great default present mode to use.
Ian Elliotta0781972015-08-21 15:09:33 -06001271 VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
Tony Barbour291d57b2016-10-21 14:47:07 -06001272
Ian Elliottb18fdde2016-10-03 12:11:12 -06001273 // There are times when you may wish to use another present mode. The
1274 // following code shows how to select them, and the comments provide some
1275 // reasons you may wish to use them.
1276 //
1277 // It should be noted that Vulkan 1.0 doesn't provide a method for
1278 // synchronizing rendering with the presentation engine's display. There
1279 // is a method provided for throttling rendering with the display, but
1280 // there are some presentation engines for which this method will not work.
1281 // If an application doesn't throttle its rendering, and if it renders much
1282 // faster than the refresh rate of the display, this can waste power on
1283 // mobile devices. That is because power is being spent rendering images
1284 // that may never be seen.
Tony Barbour291d57b2016-10-21 14:47:07 -06001285
Ian Elliottb18fdde2016-10-03 12:11:12 -06001286 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
1287 // tearing, or have some way of synchronizing their rendering with the
1288 // display.
Ian Elliottb18fdde2016-10-03 12:11:12 -06001289 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1290 // generally render a new presentable image every refresh cycle, but are
1291 // occasionally early. In this case, the application wants the new image
1292 // to be displayed instead of the previously-queued-for-presentation image
1293 // that has not yet been displayed.
Ian Elliottb18fdde2016-10-03 12:11:12 -06001294 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1295 // render a new presentable image every refresh cycle, but are occasionally
1296 // late. In this case (perhaps because of stuttering/latency concerns),
1297 // the application wants the late image to be immediately displayed, even
1298 // though that may mean some tearing.
Tony Barbour291d57b2016-10-21 14:47:07 -06001299
Dave Houlton5fa47912018-02-16 11:02:26 -07001300 if (demo->presentMode != swapchainPresentMode) {
Tony Barbour291d57b2016-10-21 14:47:07 -06001301 for (size_t i = 0; i < presentModeCount; ++i) {
1302 if (presentModes[i] == demo->presentMode) {
1303 swapchainPresentMode = demo->presentMode;
1304 break;
1305 }
Ian Elliottb18fdde2016-10-03 12:11:12 -06001306 }
1307 }
Tony Barbour291d57b2016-10-21 14:47:07 -06001308 if (swapchainPresentMode != demo->presentMode) {
1309 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1310 }
Ian Elliottaaae5352015-07-06 14:27:58 -06001311
Tony Barbour84376fe2017-01-06 15:54:22 -07001312 // Determine the number of VkImages to use in the swap chain.
1313 // Application desires to acquire 3 images at a time for triple
1314 // buffering
1315 uint32_t desiredNumOfSwapchainImages = 3;
1316 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1317 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1318 }
Ian Elliottcf7f7482016-08-19 03:46:58 -06001319 // If maxImageCount is 0, we can ask for as many images as we want;
1320 // otherwise we're limited to maxImageCount
Dave Houlton5fa47912018-02-16 11:02:26 -07001321 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
Ian Elliottaaae5352015-07-06 14:27:58 -06001322 // Application must settle for fewer images than desired:
Ian Elliottcf7f7482016-08-19 03:46:58 -06001323 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
Ian Elliottaaae5352015-07-06 14:27:58 -06001324 }
1325
Tony Barbour9fd6d352015-09-16 15:01:32 -06001326 VkSurfaceTransformFlagsKHR preTransform;
Dave Houlton5fa47912018-02-16 11:02:26 -07001327 if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
Ian Elliotta7a731c2015-12-11 15:52:12 -07001328 preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Ian Elliottaaae5352015-07-06 14:27:58 -06001329 } else {
Ian Elliottb08e0d92015-11-20 11:55:46 -07001330 preTransform = surfCapabilities.currentTransform;
Ian Elliottaaae5352015-07-06 14:27:58 -06001331 }
1332
Tony Barbour820b55b2017-03-14 08:55:46 -06001333 // Find a supported composite alpha mode - one of these is guaranteed to be set
1334 VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
1335 VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1336 VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
1337 VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
1338 VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
1339 VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
1340 };
Tony Barbour34ea9cf2017-08-14 12:02:30 -06001341 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
Tony Barbour820b55b2017-03-14 08:55:46 -06001342 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1343 compositeAlpha = compositeAlphaFlags[i];
1344 break;
1345 }
1346 }
1347
Tony Barboura2a67812016-07-18 13:21:06 -06001348 VkSwapchainCreateInfoKHR swapchain_ci = {
Ian Elliott5b97eae2015-09-22 10:20:23 -06001349 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
Chia-I Wucbb564e2015-04-16 22:02:10 +08001350 .pNext = NULL,
Ian Elliottb08e0d92015-11-20 11:55:46 -07001351 .surface = demo->surface,
Ian Elliottcf7f7482016-08-19 03:46:58 -06001352 .minImageCount = desiredNumOfSwapchainImages,
Chia-I Wucbb564e2015-04-16 22:02:10 +08001353 .imageFormat = demo->format,
Ian Elliott8528eff2015-08-07 15:56:59 -06001354 .imageColorSpace = demo->color_space,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001355 .imageExtent =
1356 {
Dave Houlton5fa47912018-02-16 11:02:26 -07001357 .width = swapchainExtent.width,
1358 .height = swapchainExtent.height,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001359 },
Ian Elliottb08e0d92015-11-20 11:55:46 -07001360 .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
Ian Elliottaaae5352015-07-06 14:27:58 -06001361 .preTransform = preTransform,
Tony Barbour820b55b2017-03-14 08:55:46 -06001362 .compositeAlpha = compositeAlpha,
Ian Elliottb08e0d92015-11-20 11:55:46 -07001363 .imageArrayLayers = 1,
1364 .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
1365 .queueFamilyIndexCount = 0,
Ian Elliott8528eff2015-08-07 15:56:59 -06001366 .pQueueFamilyIndices = NULL,
Ian Elliotta0781972015-08-21 15:09:33 -06001367 .presentMode = swapchainPresentMode,
Ian Elliottcf074d32015-10-16 18:02:43 -06001368 .oldSwapchain = oldSwapchain,
Ian Elliottaaae5352015-07-06 14:27:58 -06001369 .clipped = true,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001370 };
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -06001371 uint32_t i;
Dave Houlton5fa47912018-02-16 11:02:26 -07001372 err = demo->fpCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, &demo->swapchain);
Chia-I Wucbb564e2015-04-16 22:02:10 +08001373 assert(!err);
1374
Ian Elliottcf074d32015-10-16 18:02:43 -06001375 // If we just re-created an existing swapchain, we should destroy the old
1376 // swapchain at this point.
1377 // Note: destroying the swapchain also cleans up all its associated
1378 // presentable images once the platform is done with them.
Chia-I Wu1c4086a2015-10-26 20:04:44 +08001379 if (oldSwapchain != VK_NULL_HANDLE) {
Ian Elliottb08e0d92015-11-20 11:55:46 -07001380 demo->fpDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06001381 }
1382
Dave Houlton5fa47912018-02-16 11:02:26 -07001383 err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, NULL);
Ian Elliottaaae5352015-07-06 14:27:58 -06001384 assert(!err);
Chia-I Wucbb564e2015-04-16 22:02:10 +08001385
Dave Houlton5fa47912018-02-16 11:02:26 -07001386 VkImage *swapchainImages = (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage));
Ian Elliotta0781972015-08-21 15:09:33 -06001387 assert(swapchainImages);
Dave Houlton5fa47912018-02-16 11:02:26 -07001388 err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages);
Ian Elliottaaae5352015-07-06 14:27:58 -06001389 assert(!err);
Ian Elliottaaae5352015-07-06 14:27:58 -06001390
Dave Houlton5fa47912018-02-16 11:02:26 -07001391 demo->swapchain_image_resources =
1392 (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * demo->swapchainImageCount);
Tony Barboura72d9492017-01-11 13:35:09 -07001393 assert(demo->swapchain_image_resources);
1394
Ian Elliotta0781972015-08-21 15:09:33 -06001395 for (i = 0; i < demo->swapchainImageCount; i++) {
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001396 VkImageViewCreateInfo color_image_view = {
1397 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001398 .pNext = NULL,
1399 .format = demo->format,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001400 .components =
1401 {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001402 .r = VK_COMPONENT_SWIZZLE_IDENTITY,
1403 .g = VK_COMPONENT_SWIZZLE_IDENTITY,
1404 .b = VK_COMPONENT_SWIZZLE_IDENTITY,
1405 .a = VK_COMPONENT_SWIZZLE_IDENTITY,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001406 },
Dave Houlton5fa47912018-02-16 11:02:26 -07001407 .subresourceRange =
1408 {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001409 .viewType = VK_IMAGE_VIEW_TYPE_2D,
1410 .flags = 0,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001411 };
1412
Tony Barboura72d9492017-01-11 13:35:09 -07001413 demo->swapchain_image_resources[i].image = swapchainImages[i];
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001414
Tony Barboura72d9492017-01-11 13:35:09 -07001415 color_image_view.image = demo->swapchain_image_resources[i].image;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001416
Dave Houlton5fa47912018-02-16 11:02:26 -07001417 err = vkCreateImageView(demo->device, &color_image_view, NULL, &demo->swapchain_image_resources[i].view);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001418 assert(!err);
1419 }
Karl Schultze4dc75c2016-02-02 15:37:51 -07001420
Ian Elliottd940ca22017-03-22 08:31:27 -06001421 if (demo->VK_GOOGLE_display_timing_enabled) {
1422 VkRefreshCycleDurationGOOGLE rc_dur;
Dave Houlton5fa47912018-02-16 11:02:26 -07001423 err = demo->fpGetRefreshCycleDurationGOOGLE(demo->device, demo->swapchain, &rc_dur);
Ian Elliottd940ca22017-03-22 08:31:27 -06001424 assert(!err);
1425 demo->refresh_duration = rc_dur.refreshDuration;
1426
1427 demo->syncd_with_actual_presents = false;
1428 // Initially target 1X the refresh duration:
1429 demo->target_IPD = demo->refresh_duration;
1430 demo->refresh_duration_multiplier = 1;
1431 demo->prev_desired_present_time = 0;
1432 demo->next_present_id = 1;
Ian Elliottd940ca22017-03-22 08:31:27 -06001433 }
1434
Jason Chen5d4fee92019-04-04 12:45:29 +08001435 if (NULL != swapchainImages) {
1436 free(swapchainImages);
1437 }
1438
Mark Young04fd3d82016-01-25 14:43:50 -07001439 if (NULL != presentModes) {
1440 free(presentModes);
1441 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001442}
1443
Karl Schultze4dc75c2016-02-02 15:37:51 -07001444static void demo_prepare_depth(struct demo *demo) {
Tony Barbour72304ef2015-04-16 15:59:00 -06001445 const VkFormat depth_format = VK_FORMAT_D16_UNORM;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001446 const VkImageCreateInfo image = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001447 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001448 .pNext = NULL,
Tony Barbour72304ef2015-04-16 15:59:00 -06001449 .imageType = VK_IMAGE_TYPE_2D,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001450 .format = depth_format,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001451 .extent = {demo->width, demo->height, 1},
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001452 .mipLevels = 1,
Courtney Goeltzenleuchterdff021f2015-10-21 17:57:31 -06001453 .arrayLayers = 1,
Chia-I Wu3ede9462015-10-31 00:31:16 +08001454 .samples = VK_SAMPLE_COUNT_1_BIT,
Tony Barbour72304ef2015-04-16 15:59:00 -06001455 .tiling = VK_IMAGE_TILING_OPTIMAL,
Courtney Goeltzenleuchter4e368ee2015-09-10 14:14:11 -06001456 .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001457 .flags = 0,
1458 };
Dominik Witczak2fe1c702015-09-22 18:25:33 +02001459
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001460 VkImageViewCreateInfo view = {
1461 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001462 .pNext = NULL,
Chia-I Wu1c4086a2015-10-26 20:04:44 +08001463 .image = VK_NULL_HANDLE,
Courtney Goeltzenleuchter556ee322015-07-15 17:41:38 -06001464 .format = depth_format,
Dave Houlton5fa47912018-02-16 11:02:26 -07001465 .subresourceRange =
1466 {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001467 .flags = 0,
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001468 .viewType = VK_IMAGE_VIEW_TYPE_2D,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001469 };
Mike Stroyanebae8322015-04-17 12:36:38 -06001470
Mark Young43c08f82021-11-30 16:38:25 -07001471 if (demo->force_errors) {
1472 // Intentionally force a bad pNext value to generate a validation layer error
1473 view.pNext = &image;
1474 }
1475
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001476 VkMemoryRequirements mem_reqs;
Tony Barbourfdc2d352015-04-22 09:02:32 -06001477 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001478 bool U_ASSERT_ONLY pass;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001479
1480 demo->depth.format = depth_format;
1481
1482 /* create image */
Karl Schultze4dc75c2016-02-02 15:37:51 -07001483 err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001484 assert(!err);
1485
Karl Schultze4dc75c2016-02-02 15:37:51 -07001486 vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
Tony Barbourcb59a5d2015-10-23 10:53:30 -06001487 assert(!err);
Mark Lobodzinskieadf9982015-07-02 16:49:40 -06001488
Chia-I Wuf48700b2015-11-10 16:21:09 +08001489 demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
Dominik Witczak2fe1c702015-09-22 18:25:33 +02001490 demo->depth.mem_alloc.pNext = NULL;
1491 demo->depth.mem_alloc.allocationSize = mem_reqs.size;
1492 demo->depth.mem_alloc.memoryTypeIndex = 0;
1493
Dave Houlton5fa47912018-02-16 11:02:26 -07001494 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001495 &demo->depth.mem_alloc.memoryTypeIndex);
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001496 assert(pass);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001497
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001498 /* allocate memory */
Dave Houlton5fa47912018-02-16 11:02:26 -07001499 err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, &demo->depth.mem);
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001500 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001501
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001502 /* bind memory */
Dave Houlton5fa47912018-02-16 11:02:26 -07001503 err = vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001504 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001505
1506 /* create image view */
1507 view.image = demo->depth.image;
Chia-I Wu63636062015-10-26 21:10:41 +08001508 err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001509 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001510}
1511
Karl Schultzb7940402018-05-29 13:09:22 -06001512/* Convert ppm image data from header file into RGBA texture image */
1513#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07001514bool loadTexture(const char *filename, uint8_t *rgba_data, VkSubresourceLayout *layout, int32_t *width, int32_t *height) {
Karl Schultzb7940402018-05-29 13:09:22 -06001515 (void)filename;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001516 char *cPtr;
Dave Houlton5fa47912018-02-16 11:02:26 -07001517 cPtr = (char *)lunarg_ppm;
1518 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001519 return false;
1520 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001521 while (strncmp(cPtr++, "\n", 1))
1522 ;
Alexandre BACQUART9063e2a2016-06-17 11:30:32 -06001523 sscanf(cPtr, "%u %u", width, height);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001524 if (rgba_data == NULL) {
1525 return true;
1526 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001527 while (strncmp(cPtr++, "\n", 1))
1528 ;
1529 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001530 return false;
1531 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001532 while (strncmp(cPtr++, "\n", 1))
1533 ;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001534 for (int y = 0; y < *height; y++) {
1535 uint8_t *rowPtr = rgba_data;
1536 for (int x = 0; x < *width; x++) {
1537 memcpy(rowPtr, cPtr, 3);
1538 rowPtr[3] = 255; /* Alpha of 1 */
1539 rowPtr += 4;
1540 cPtr += 3;
1541 }
1542 rgba_data += layout->rowPitch;
1543 }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001544 return true;
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -06001545}
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -06001546
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001547static void demo_prepare_texture_buffer(struct demo *demo, const char *filename, struct texture_object *tex_obj) {
1548 int32_t tex_width;
1549 int32_t tex_height;
1550 VkResult U_ASSERT_ONLY err;
1551 bool U_ASSERT_ONLY pass;
1552
1553 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
1554 ERR_EXIT("Failed to load textures", "Load Texture Failure");
1555 }
1556
1557 tex_obj->tex_width = tex_width;
1558 tex_obj->tex_height = tex_height;
1559
1560 const VkBufferCreateInfo buffer_create_info = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
1561 .pNext = NULL,
1562 .flags = 0,
1563 .size = tex_width * tex_height * 4,
1564 .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1565 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1566 .queueFamilyIndexCount = 0,
1567 .pQueueFamilyIndices = NULL};
1568
1569 err = vkCreateBuffer(demo->device, &buffer_create_info, NULL, &tex_obj->buffer);
1570 assert(!err);
1571
1572 VkMemoryRequirements mem_reqs;
1573 vkGetBufferMemoryRequirements(demo->device, tex_obj->buffer, &mem_reqs);
1574
1575 tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1576 tex_obj->mem_alloc.pNext = NULL;
1577 tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1578 tex_obj->mem_alloc.memoryTypeIndex = 0;
1579
1580 VkFlags requirements = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
1581 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
1582 assert(pass);
1583
1584 err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
1585 assert(!err);
1586
1587 /* bind memory */
1588 err = vkBindBufferMemory(demo->device, tex_obj->buffer, tex_obj->mem, 0);
1589 assert(!err);
1590
1591 VkSubresourceLayout layout;
1592 memset(&layout, 0, sizeof(layout));
1593 layout.rowPitch = tex_width * 4;
1594
1595 void *data;
1596 err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
1597 assert(!err);
1598
1599 if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1600 fprintf(stderr, "Error loading texture: %s\n", filename);
1601 }
1602
1603 vkUnmapMemory(demo->device, tex_obj->mem);
1604}
1605
Dave Houlton5fa47912018-02-16 11:02:26 -07001606static void demo_prepare_texture_image(struct demo *demo, const char *filename, struct texture_object *tex_obj,
1607 VkImageTiling tiling, VkImageUsageFlags usage, VkFlags required_props) {
Mike Stroyan8b89e072015-06-15 14:21:03 -06001608 const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -06001609 int32_t tex_width;
1610 int32_t tex_height;
Tony Barbourfdc2d352015-04-22 09:02:32 -06001611 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001612 bool U_ASSERT_ONLY pass;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001613
Karl Schultze4dc75c2016-02-02 15:37:51 -07001614 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001615 ERR_EXIT("Failed to load textures", "Load Texture Failure");
David Pinedo30bd71d2015-04-23 08:16:57 -06001616 }
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001617
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -06001618 tex_obj->tex_width = tex_width;
1619 tex_obj->tex_height = tex_height;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001620
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001621 const VkImageCreateInfo image_create_info = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001622 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001623 .pNext = NULL,
Tony Barbour72304ef2015-04-16 15:59:00 -06001624 .imageType = VK_IMAGE_TYPE_2D,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001625 .format = tex_format,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001626 .extent = {tex_width, tex_height, 1},
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001627 .mipLevels = 1,
Courtney Goeltzenleuchterdff021f2015-10-21 17:57:31 -06001628 .arrayLayers = 1,
Chia-I Wu3ede9462015-10-31 00:31:16 +08001629 .samples = VK_SAMPLE_COUNT_1_BIT,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001630 .tiling = tiling,
Courtney Goeltzenleuchterc56c36a2015-04-21 09:31:23 -06001631 .usage = usage,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001632 .flags = 0,
Tobin Ehlisf07d9552016-02-11 17:49:23 -07001633 .initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001634 };
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001635
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001636 VkMemoryRequirements mem_reqs;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001637
Dave Houlton5fa47912018-02-16 11:02:26 -07001638 err = vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001639 assert(!err);
1640
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06001641 vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs);
Piers Daniell735ee532015-02-23 16:23:13 -07001642
Chia-I Wuf48700b2015-11-10 16:21:09 +08001643 tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
Dominik Witczak2fe1c702015-09-22 18:25:33 +02001644 tex_obj->mem_alloc.pNext = NULL;
1645 tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1646 tex_obj->mem_alloc.memoryTypeIndex = 0;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001647
Dave Houlton5fa47912018-02-16 11:02:26 -07001648 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001649 assert(pass);
Mark Lobodzinskieadf9982015-07-02 16:49:40 -06001650
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001651 /* allocate memory */
Dave Houlton5fa47912018-02-16 11:02:26 -07001652 err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001653 assert(!err);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001654
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001655 /* bind memory */
Karl Schultze4dc75c2016-02-02 15:37:51 -07001656 err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0);
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001657 assert(!err);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001658
Tony Barbour8a9f62a2015-10-15 12:42:56 -06001659 if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001660 const VkImageSubresource subres = {
Chia-I Wua0141432015-10-27 19:55:05 +08001661 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001662 .mipLevel = 0,
Courtney Goeltzenleuchterfc465b82015-09-10 16:38:41 -06001663 .arrayLayer = 0,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001664 };
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001665 VkSubresourceLayout layout;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001666 void *data;
1667
Dave Houlton5fa47912018-02-16 11:02:26 -07001668 vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001669
Dave Houlton5fa47912018-02-16 11:02:26 -07001670 err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001671 assert(!err);
1672
1673 if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1674 fprintf(stderr, "Error loading texture: %s\n", filename);
1675 }
1676
Mark Lobodzinskie4c92a62015-09-07 13:59:43 -06001677 vkUnmapMemory(demo->device, tex_obj->mem);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001678 }
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -06001679
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001680 tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001681}
1682
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001683static void demo_destroy_texture(struct demo *demo, struct texture_object *tex_objs) {
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001684 /* clean up staging resources */
Chia-I Wu63636062015-10-26 21:10:41 +08001685 vkFreeMemory(demo->device, tex_objs->mem, NULL);
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001686 if (tex_objs->image) vkDestroyImage(demo->device, tex_objs->image, NULL);
1687 if (tex_objs->buffer) vkDestroyBuffer(demo->device, tex_objs->buffer, NULL);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001688}
1689
Karl Schultze4dc75c2016-02-02 15:37:51 -07001690static void demo_prepare_textures(struct demo *demo) {
Tony Barbour72304ef2015-04-16 15:59:00 -06001691 const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001692 VkFormatProperties props;
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -06001693 uint32_t i;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001694
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06001695 vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001696
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001697 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06001698 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001699
Dave Houlton5fa47912018-02-16 11:02:26 -07001700 if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) {
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001701 /* Device can texture using linear textures */
Dave Houlton5fa47912018-02-16 11:02:26 -07001702 demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT,
1703 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
Tony Barbour5ff13182016-10-19 13:58:29 -06001704 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
1705 // shader to run until layout transition completes
Dave Houlton5fa47912018-02-16 11:02:26 -07001706 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1707 demo->textures[i].imageLayout, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
Tony Barbour5ff13182016-10-19 13:58:29 -06001708 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
Tony Barbour16156cb2016-10-19 14:15:49 -06001709 demo->staging_texture.image = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07001710 } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001711 /* Must use staging buffer to copy linear texture to optimized */
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001712
Tony Barbour16156cb2016-10-19 14:15:49 -06001713 memset(&demo->staging_texture, 0, sizeof(demo->staging_texture));
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001714 demo_prepare_texture_buffer(demo, tex_files[i], &demo->staging_texture);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001715
Dave Houlton5fa47912018-02-16 11:02:26 -07001716 demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL,
1717 (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
1718 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001719
Dave Houlton5fa47912018-02-16 11:02:26 -07001720 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1721 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
Tony Barbour5ff13182016-10-19 13:58:29 -06001722 VK_PIPELINE_STAGE_TRANSFER_BIT);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001723
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001724 VkBufferImageCopy copy_region = {
1725 .bufferOffset = 0,
1726 .bufferRowLength = demo->staging_texture.tex_width,
1727 .bufferImageHeight = demo->staging_texture.tex_height,
1728 .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
1729 .imageOffset = {0, 0, 0},
1730 .imageExtent = {demo->staging_texture.tex_width, demo->staging_texture.tex_height, 1},
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001731 };
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001732
1733 vkCmdCopyBufferToImage(demo->cmd, demo->staging_texture.buffer, demo->textures[i].image,
1734 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001735
Dave Houlton5fa47912018-02-16 11:02:26 -07001736 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1737 demo->textures[i].imageLayout, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
Tony Barbour5ff13182016-10-19 13:58:29 -06001738 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001739
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001740 } else {
Mike Stroyan8b89e072015-06-15 14:21:03 -06001741 /* Can't support VK_FORMAT_R8G8B8A8_UNORM !? */
1742 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001743 }
1744
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001745 const VkSamplerCreateInfo sampler = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001746 .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001747 .pNext = NULL,
Chia-I Wu6ef8c3b2015-10-26 16:49:32 +08001748 .magFilter = VK_FILTER_NEAREST,
1749 .minFilter = VK_FILTER_NEAREST,
Jon Ashburn0bec67e2016-01-11 13:12:43 -07001750 .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
Chia-I Wu6555f3f2015-10-26 17:32:47 +08001751 .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1752 .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1753 .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001754 .mipLodBias = 0.0f,
Jon Ashburn55e3fb02015-12-14 14:59:20 -07001755 .anisotropyEnable = VK_FALSE,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001756 .maxAnisotropy = 1,
Tony Barbour72304ef2015-04-16 15:59:00 -06001757 .compareOp = VK_COMPARE_OP_NEVER,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001758 .minLod = 0.0f,
1759 .maxLod = 0.0f,
Tony Barbourcb530c72015-06-25 16:56:44 -06001760 .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
Mark Lobodzinski644dc492015-09-01 15:42:56 -06001761 .unnormalizedCoordinates = VK_FALSE,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001762 };
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -06001763
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001764 VkImageViewCreateInfo view = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001765 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001766 .pNext = NULL,
Chia-I Wu1c4086a2015-10-26 20:04:44 +08001767 .image = VK_NULL_HANDLE,
Tony Barbour72304ef2015-04-16 15:59:00 -06001768 .viewType = VK_IMAGE_VIEW_TYPE_2D,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001769 .format = tex_format,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001770 .components =
1771 {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001772 VK_COMPONENT_SWIZZLE_IDENTITY,
1773 VK_COMPONENT_SWIZZLE_IDENTITY,
1774 VK_COMPONENT_SWIZZLE_IDENTITY,
1775 VK_COMPONENT_SWIZZLE_IDENTITY,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001776 },
1777 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001778 .flags = 0,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001779 };
Jon Ashburnb2a66652015-01-16 09:37:43 -07001780
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001781 /* create sampler */
Dave Houlton5fa47912018-02-16 11:02:26 -07001782 err = vkCreateSampler(demo->device, &sampler, NULL, &demo->textures[i].sampler);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001783 assert(!err);
1784
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001785 /* create image view */
1786 view.image = demo->textures[i].image;
Dave Houlton5fa47912018-02-16 11:02:26 -07001787 err = vkCreateImageView(demo->device, &view, NULL, &demo->textures[i].view);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001788 assert(!err);
1789 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001790}
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001791
Tony Barboura72d9492017-01-11 13:35:09 -07001792void demo_prepare_cube_data_buffers(struct demo *demo) {
Courtney Goeltzenleuchter28c4d5f2015-04-14 18:48:46 -06001793 VkBufferCreateInfo buf_info;
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001794 VkMemoryRequirements mem_reqs;
Tony Barboura72d9492017-01-11 13:35:09 -07001795 VkMemoryAllocateInfo mem_alloc;
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001796 mat4x4 MVP, VP;
Tony Barbourfdc2d352015-04-22 09:02:32 -06001797 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001798 bool U_ASSERT_ONLY pass;
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001799 struct vktexcube_vs_uniform data;
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001800
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001801 mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001802 mat4x4_mul(MVP, VP, demo->model_matrix);
1803 memcpy(data.mvp, MVP, sizeof(MVP));
Karl Schultze4dc75c2016-02-02 15:37:51 -07001804 // dumpMatrix("MVP", MVP);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001805
Karl Schultza2615462017-01-20 13:19:20 -07001806 for (unsigned int i = 0; i < 12 * 3; i++) {
Karl Schultze4dc75c2016-02-02 15:37:51 -07001807 data.position[i][0] = g_vertex_buffer_data[i * 3];
1808 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1809 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001810 data.position[i][3] = 1.0f;
Karl Schultze4dc75c2016-02-02 15:37:51 -07001811 data.attr[i][0] = g_uv_buffer_data[2 * i];
1812 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001813 data.attr[i][2] = 0;
1814 data.attr[i][3] = 0;
1815 }
1816
Chia-I Wu8ea21c72015-01-01 07:55:04 +08001817 memset(&buf_info, 0, sizeof(buf_info));
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001818 buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
Courtney Goeltzenleuchter42a078d2015-04-15 15:29:59 -06001819 buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
Cody Northrop91807302015-07-16 10:29:32 -06001820 buf_info.size = sizeof(data);
Chia-I Wu8ea21c72015-01-01 07:55:04 +08001821
Tony Barboura72d9492017-01-11 13:35:09 -07001822 for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001823 err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->swapchain_image_resources[i].uniform_buffer);
Tony Barboura72d9492017-01-11 13:35:09 -07001824 assert(!err);
Chia-I Wu8ea21c72015-01-01 07:55:04 +08001825
Dave Houlton5fa47912018-02-16 11:02:26 -07001826 vkGetBufferMemoryRequirements(demo->device, demo->swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Dominik Witczak2fe1c702015-09-22 18:25:33 +02001827
Tony Barboura72d9492017-01-11 13:35:09 -07001828 mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1829 mem_alloc.pNext = NULL;
1830 mem_alloc.allocationSize = mem_reqs.size;
1831 mem_alloc.memoryTypeIndex = 0;
1832
Dave Houlton5fa47912018-02-16 11:02:26 -07001833 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
1834 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1835 &mem_alloc.memoryTypeIndex);
Tony Barboura72d9492017-01-11 13:35:09 -07001836 assert(pass);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001837
Dave Houlton5fa47912018-02-16 11:02:26 -07001838 err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->swapchain_image_resources[i].uniform_memory);
Tony Barboura72d9492017-01-11 13:35:09 -07001839 assert(!err);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001840
Tony-LunarG37af49f2019-12-19 12:04:19 -07001841 err = vkMapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, 0,
1842 &demo->swapchain_image_resources[i].uniform_memory_ptr);
Tony Barboura72d9492017-01-11 13:35:09 -07001843 assert(!err);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001844
Tony-LunarG37af49f2019-12-19 12:04:19 -07001845 memcpy(demo->swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001846
Tony Barboura72d9492017-01-11 13:35:09 -07001847 err = vkBindBufferMemory(demo->device, demo->swapchain_image_resources[i].uniform_buffer,
Dave Houlton5fa47912018-02-16 11:02:26 -07001848 demo->swapchain_image_resources[i].uniform_memory, 0);
Tony Barboura72d9492017-01-11 13:35:09 -07001849 assert(!err);
1850 }
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001851}
1852
Karl Schultze4dc75c2016-02-02 15:37:51 -07001853static void demo_prepare_descriptor_layout(struct demo *demo) {
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001854 const VkDescriptorSetLayoutBinding layout_bindings[2] = {
Dave Houlton5fa47912018-02-16 11:02:26 -07001855 [0] =
1856 {
1857 .binding = 0,
1858 .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1859 .descriptorCount = 1,
1860 .stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
1861 .pImmutableSamplers = NULL,
1862 },
1863 [1] =
1864 {
1865 .binding = 1,
1866 .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1867 .descriptorCount = DEMO_TEXTURE_COUNT,
1868 .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
1869 .pImmutableSamplers = NULL,
1870 },
Chia-I Wua2aa8632015-03-26 15:04:41 +08001871 };
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001872 const VkDescriptorSetLayoutCreateInfo descriptor_layout = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001873 .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
Chia-I Wu6a3c8972015-01-04 16:27:24 +08001874 .pNext = NULL,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001875 .bindingCount = 2,
Jon Ashburn238f3432015-12-30 18:01:16 -07001876 .pBindings = layout_bindings,
Chia-I Wu6a3c8972015-01-04 16:27:24 +08001877 };
Tony Barbourfdc2d352015-04-22 09:02:32 -06001878 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001879
Dave Houlton5fa47912018-02-16 11:02:26 -07001880 err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, &demo->desc_layout);
Chia-I Wub58c24a2015-03-26 15:27:55 +08001881 assert(!err);
1882
Mark Lobodzinski1cfc7722015-04-17 14:11:39 -05001883 const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {
Karl Schultze4dc75c2016-02-02 15:37:51 -07001884 .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1885 .pNext = NULL,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001886 .setLayoutCount = 1,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001887 .pSetLayouts = &demo->desc_layout,
Mark Lobodzinski1cfc7722015-04-17 14:11:39 -05001888 };
1889
Dave Houlton5fa47912018-02-16 11:02:26 -07001890 err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001891 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001892}
1893
Karl Schultze4dc75c2016-02-02 15:37:51 -07001894static void demo_prepare_render_pass(struct demo *demo) {
Tony Barbourdb30e4b2016-10-11 11:41:05 -06001895 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1896 // because at the start of the renderpass, we don't care about their contents.
1897 // At the start of the subpass, the color attachment's layout will be transitioned
1898 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1899 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1900 // the renderpass, the color attachment's layout will be transitioned to
1901 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1902 // the renderpass, no barriers are necessary.
Chia-I Wua74c5b22015-07-07 11:50:03 +08001903 const VkAttachmentDescription attachments[2] = {
Dave Houlton5fa47912018-02-16 11:02:26 -07001904 [0] =
1905 {
1906 .format = demo->format,
1907 .flags = 0,
1908 .samples = VK_SAMPLE_COUNT_1_BIT,
1909 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1910 .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
1911 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1912 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1913 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1914 .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
1915 },
1916 [1] =
1917 {
1918 .format = demo->depth.format,
1919 .flags = 0,
1920 .samples = VK_SAMPLE_COUNT_1_BIT,
1921 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1922 .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1923 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1924 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1925 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1926 .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1927 },
Chia-I Wuf973e322015-07-08 13:34:24 +08001928 };
Chia-I Wua74c5b22015-07-07 11:50:03 +08001929 const VkAttachmentReference color_reference = {
Dave Houlton5fa47912018-02-16 11:02:26 -07001930 .attachment = 0,
1931 .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
Chia-I Wua74c5b22015-07-07 11:50:03 +08001932 };
Chia-I Wu6555f3f2015-10-26 17:32:47 +08001933 const VkAttachmentReference depth_reference = {
1934 .attachment = 1,
1935 .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1936 };
Chia-I Wua74c5b22015-07-07 11:50:03 +08001937 const VkSubpassDescription subpass = {
Chia-I Wua74c5b22015-07-07 11:50:03 +08001938 .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
1939 .flags = 0,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001940 .inputAttachmentCount = 0,
Cody Northrop945bb832015-08-04 11:16:41 -06001941 .pInputAttachments = NULL,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001942 .colorAttachmentCount = 1,
Cody Northrop945bb832015-08-04 11:16:41 -06001943 .pColorAttachments = &color_reference,
1944 .pResolveAttachments = NULL,
Chia-I Wu6555f3f2015-10-26 17:32:47 +08001945 .pDepthStencilAttachment = &depth_reference,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001946 .preserveAttachmentCount = 0,
Cody Northrop945bb832015-08-04 11:16:41 -06001947 .pPreserveAttachments = NULL,
Chia-I Wua74c5b22015-07-07 11:50:03 +08001948 };
Tony-LunarG495604b2019-06-13 15:32:05 -06001949
1950 VkSubpassDependency attachmentDependencies[2] = {
1951 [0] =
1952 {
1953 // Depth buffer is shared between swapchain images
1954 .srcSubpass = VK_SUBPASS_EXTERNAL,
1955 .dstSubpass = 0,
1956 .srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
1957 .dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
1958 .srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1959 .dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1960 .dependencyFlags = 0,
1961 },
1962 [1] =
1963 {
1964 // Image Layout Transition
1965 .srcSubpass = VK_SUBPASS_EXTERNAL,
1966 .dstSubpass = 0,
1967 .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
1968 .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
1969 .srcAccessMask = 0,
1970 .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT,
1971 .dependencyFlags = 0,
1972 },
1973 };
1974
Chia-I Wuf973e322015-07-08 13:34:24 +08001975 const VkRenderPassCreateInfo rp_info = {
1976 .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
1977 .pNext = NULL,
Tony Barboura860ce12016-11-21 12:56:25 -07001978 .flags = 0,
Chia-I Wua74c5b22015-07-07 11:50:03 +08001979 .attachmentCount = 2,
1980 .pAttachments = attachments,
1981 .subpassCount = 1,
1982 .pSubpasses = &subpass,
Tony-LunarG495604b2019-06-13 15:32:05 -06001983 .dependencyCount = 2,
1984 .pDependencies = attachmentDependencies,
Chia-I Wuf973e322015-07-08 13:34:24 +08001985 };
Chia-I Wua74c5b22015-07-07 11:50:03 +08001986 VkResult U_ASSERT_ONLY err;
Chia-I Wuf973e322015-07-08 13:34:24 +08001987
Chia-I Wu63636062015-10-26 21:10:41 +08001988 err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass);
Chia-I Wuf973e322015-07-08 13:34:24 +08001989 assert(!err);
1990}
1991
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001992static VkShaderModule demo_prepare_shader_module(struct demo *demo, const uint32_t *code, size_t size) {
Chia-I Wu46176f12015-10-31 00:31:16 +08001993 VkShaderModule module;
Courtney Goeltzenleuchtera80a1a92015-06-24 18:24:19 -06001994 VkShaderModuleCreateInfo moduleCreateInfo;
Courtney Goeltzenleuchterd3cdaaf2015-12-17 09:53:29 -07001995 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001996
Courtney Goeltzenleuchtera80a1a92015-06-24 18:24:19 -06001997 moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1998 moduleCreateInfo.pNext = NULL;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001999 moduleCreateInfo.flags = 0;
Courtney Goeltzenleuchtera95e3052015-10-30 15:19:27 -06002000 moduleCreateInfo.codeSize = size;
2001 moduleCreateInfo.pCode = code;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002002
Courtney Goeltzenleuchtera95e3052015-10-30 15:19:27 -06002003 err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module);
2004 assert(!err);
Chia-I Wu46176f12015-10-31 00:31:16 +08002005
2006 return module;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002007}
2008
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002009static void demo_prepare_vs(struct demo *demo) {
2010 const uint32_t vs_code[] = {
2011#include "cube.vert.inc"
2012 };
2013 demo->vert_shader_module = demo_prepare_shader_module(demo, vs_code, sizeof(vs_code));
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002014}
2015
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002016static void demo_prepare_fs(struct demo *demo) {
2017 const uint32_t fs_code[] = {
2018#include "cube.frag.inc"
2019 };
2020 demo->frag_shader_module = demo_prepare_shader_module(demo, fs_code, sizeof(fs_code));
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002021}
2022
Karl Schultze4dc75c2016-02-02 15:37:51 -07002023static void demo_prepare_pipeline(struct demo *demo) {
Tony-LunarG8ee48dc2020-05-07 10:02:58 -06002024#define NUM_DYNAMIC_STATES 2 /*Viewport + Scissor*/
2025
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06002026 VkGraphicsPipelineCreateInfo pipeline;
Jon Ashburnc4ab7af2015-07-09 15:02:25 -06002027 VkPipelineCacheCreateInfo pipelineCache;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002028 VkPipelineVertexInputStateCreateInfo vi;
Tony Barbour194bf282015-07-10 15:29:03 -06002029 VkPipelineInputAssemblyStateCreateInfo ia;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002030 VkPipelineRasterizationStateCreateInfo rs;
2031 VkPipelineColorBlendStateCreateInfo cb;
2032 VkPipelineDepthStencilStateCreateInfo ds;
2033 VkPipelineViewportStateCreateInfo vp;
2034 VkPipelineMultisampleStateCreateInfo ms;
Tony-LunarG8ee48dc2020-05-07 10:02:58 -06002035 VkDynamicState dynamicStateEnables[NUM_DYNAMIC_STATES];
Karl Schultze4dc75c2016-02-02 15:37:51 -07002036 VkPipelineDynamicStateCreateInfo dynamicState;
Tony Barbourfdc2d352015-04-22 09:02:32 -06002037 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002038
Piers Daniellba839d12015-09-29 13:01:09 -06002039 memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
2040 memset(&dynamicState, 0, sizeof dynamicState);
2041 dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
2042 dynamicState.pDynamicStates = dynamicStateEnables;
2043
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002044 memset(&pipeline, 0, sizeof(pipeline));
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002045 pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
Mark Lobodzinski1cfc7722015-04-17 14:11:39 -05002046 pipeline.layout = demo->pipeline_layout;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002047
Jason Ekstrand515b7ae2015-10-15 17:15:25 -07002048 memset(&vi, 0, sizeof(vi));
2049 vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
2050
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002051 memset(&ia, 0, sizeof(ia));
Tony Barbour194bf282015-07-10 15:29:03 -06002052 ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
Tony Barbour72304ef2015-04-16 15:59:00 -06002053 ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002054
2055 memset(&rs, 0, sizeof(rs));
Chia-I Wuf051d262015-10-27 19:25:11 +08002056 rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
2057 rs.polygonMode = VK_POLYGON_MODE_FILL;
Chia-I Wu6555f3f2015-10-26 17:32:47 +08002058 rs.cullMode = VK_CULL_MODE_BACK_BIT;
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002059 rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
Courtney Goeltzenleuchter0db2c912015-10-15 12:57:38 -06002060 rs.depthClampEnable = VK_FALSE;
Cody Northrop709c1742015-08-17 11:10:49 -06002061 rs.rasterizerDiscardEnable = VK_FALSE;
2062 rs.depthBiasEnable = VK_FALSE;
Mark Young8749e2e2016-03-31 14:56:43 -06002063 rs.lineWidth = 1.0f;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002064
2065 memset(&cb, 0, sizeof(cb));
Tony Barbour194bf282015-07-10 15:29:03 -06002066 cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
2067 VkPipelineColorBlendAttachmentState att_state[1];
Tony Barbour29645d02015-01-16 14:27:35 -07002068 memset(att_state, 0, sizeof(att_state));
Chia-I Wuf051d262015-10-27 19:25:11 +08002069 att_state[0].colorWriteMask = 0xf;
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002070 att_state[0].blendEnable = VK_FALSE;
Tony Barbour29645d02015-01-16 14:27:35 -07002071 cb.attachmentCount = 1;
2072 cb.pAttachments = att_state;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002073
Tony Barbour29645d02015-01-16 14:27:35 -07002074 memset(&vp, 0, sizeof(vp));
Tony Barbour194bf282015-07-10 15:29:03 -06002075 vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
Tony Barbour72304ef2015-04-16 15:59:00 -06002076 vp.viewportCount = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07002077 dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT;
Piers Daniellba839d12015-09-29 13:01:09 -06002078 vp.scissorCount = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07002079 dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR;
Tony Barbour29645d02015-01-16 14:27:35 -07002080
2081 memset(&ds, 0, sizeof(ds));
Tony Barbour194bf282015-07-10 15:29:03 -06002082 ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002083 ds.depthTestEnable = VK_TRUE;
2084 ds.depthWriteEnable = VK_TRUE;
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002085 ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
Cody Northrop5e4125d2015-08-26 10:01:32 -06002086 ds.depthBoundsTestEnable = VK_FALSE;
Chia-I Wuf051d262015-10-27 19:25:11 +08002087 ds.back.failOp = VK_STENCIL_OP_KEEP;
2088 ds.back.passOp = VK_STENCIL_OP_KEEP;
2089 ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002090 ds.stencilTestEnable = VK_FALSE;
Tony Barbour29645d02015-01-16 14:27:35 -07002091 ds.front = ds.back;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002092
Tony Barbour29645d02015-01-16 14:27:35 -07002093 memset(&ms, 0, sizeof(ms));
Tony Barbour194bf282015-07-10 15:29:03 -06002094 ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
Cody Northrop011546b2015-08-04 14:34:54 -06002095 ms.pSampleMask = NULL;
Chia-I Wu3ede9462015-10-31 00:31:16 +08002096 ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002097
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002098 demo_prepare_vs(demo);
2099 demo_prepare_fs(demo);
2100
Mark Lobodzinski521d7762015-06-23 15:11:57 -06002101 // Two stages: vs and fs
Mark Lobodzinski521d7762015-06-23 15:11:57 -06002102 VkPipelineShaderStageCreateInfo shaderStages[2];
2103 memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
2104
Karl Schultze4dc75c2016-02-02 15:37:51 -07002105 shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2106 shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002107 shaderStages[0].module = demo->vert_shader_module;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002108 shaderStages[0].pName = "main";
Mark Lobodzinski521d7762015-06-23 15:11:57 -06002109
Karl Schultze4dc75c2016-02-02 15:37:51 -07002110 shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2111 shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002112 shaderStages[1].module = demo->frag_shader_module;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002113 shaderStages[1].pName = "main";
Mark Lobodzinski521d7762015-06-23 15:11:57 -06002114
Jon Ashburnc4ab7af2015-07-09 15:02:25 -06002115 memset(&pipelineCache, 0, sizeof(pipelineCache));
2116 pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002117
Dave Houlton5fa47912018-02-16 11:02:26 -07002118 err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache);
Jon Ashburnc4ab7af2015-07-09 15:02:25 -06002119 assert(!err);
Tony Barbour194bf282015-07-10 15:29:03 -06002120
Karl Schultze4dc75c2016-02-02 15:37:51 -07002121 pipeline.pVertexInputState = &vi;
Tony Barbour194bf282015-07-10 15:29:03 -06002122 pipeline.pInputAssemblyState = &ia;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002123 pipeline.pRasterizationState = &rs;
2124 pipeline.pColorBlendState = &cb;
2125 pipeline.pMultisampleState = &ms;
2126 pipeline.pViewportState = &vp;
2127 pipeline.pDepthStencilState = &ds;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002128 pipeline.stageCount = ARRAY_SIZE(shaderStages);
Karl Schultze4dc75c2016-02-02 15:37:51 -07002129 pipeline.pStages = shaderStages;
2130 pipeline.renderPass = demo->render_pass;
2131 pipeline.pDynamicState = &dynamicState;
Tony Barbour194bf282015-07-10 15:29:03 -06002132
Courtney Goeltzenleuchterd311fd02015-08-13 16:55:04 -06002133 pipeline.renderPass = demo->render_pass;
2134
Dave Houlton5fa47912018-02-16 11:02:26 -07002135 err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, &pipeline, NULL, &demo->pipeline);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002136 assert(!err);
2137
Chia-I Wu63636062015-10-26 21:10:41 +08002138 vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL);
2139 vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002140}
2141
Karl Schultze4dc75c2016-02-02 15:37:51 -07002142static void demo_prepare_descriptor_pool(struct demo *demo) {
Chia-I Wuf051d262015-10-27 19:25:11 +08002143 const VkDescriptorPoolSize type_counts[2] = {
Dave Houlton5fa47912018-02-16 11:02:26 -07002144 [0] =
2145 {
2146 .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
2147 .descriptorCount = demo->swapchainImageCount,
2148 },
2149 [1] =
2150 {
2151 .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2152 .descriptorCount = demo->swapchainImageCount * DEMO_TEXTURE_COUNT,
2153 },
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002154 };
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06002155 const VkDescriptorPoolCreateInfo descriptor_pool = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002156 .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002157 .pNext = NULL,
Tony Barboura72d9492017-01-11 13:35:09 -07002158 .maxSets = demo->swapchainImageCount,
Chia-I Wuf051d262015-10-27 19:25:11 +08002159 .poolSizeCount = 2,
2160 .pPoolSizes = type_counts,
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002161 };
Tony Barbourfdc2d352015-04-22 09:02:32 -06002162 VkResult U_ASSERT_ONLY err;
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002163
Dave Houlton5fa47912018-02-16 11:02:26 -07002164 err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, &demo->desc_pool);
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002165 assert(!err);
2166}
2167
Karl Schultze4dc75c2016-02-02 15:37:51 -07002168static void demo_prepare_descriptor_set(struct demo *demo) {
Courtney Goeltzenleuchterc3ad65e2015-10-23 13:38:14 -06002169 VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
Chia-I Wuae721ba2015-05-25 16:27:55 +08002170 VkWriteDescriptorSet writes[2];
Tony Barbourfdc2d352015-04-22 09:02:32 -06002171 VkResult U_ASSERT_ONLY err;
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002172
Dave Houlton5fa47912018-02-16 11:02:26 -07002173 VkDescriptorSetAllocateInfo alloc_info = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
2174 .pNext = NULL,
2175 .descriptorPool = demo->desc_pool,
2176 .descriptorSetCount = 1,
2177 .pSetLayouts = &demo->desc_layout};
Tony Barboura72d9492017-01-11 13:35:09 -07002178
2179 VkDescriptorBufferInfo buffer_info;
2180 buffer_info.offset = 0;
2181 buffer_info.range = sizeof(struct vktexcube_vs_uniform);
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002182
Chia-I Wuae721ba2015-05-25 16:27:55 +08002183 memset(&tex_descs, 0, sizeof(tex_descs));
Karl Schultza2615462017-01-20 13:19:20 -07002184 for (unsigned int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
Courtney Goeltzenleuchterc3ad65e2015-10-23 13:38:14 -06002185 tex_descs[i].sampler = demo->textures[i].sampler;
2186 tex_descs[i].imageView = demo->textures[i].view;
Karl Schultze88bc842018-09-11 16:23:14 -06002187 tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002188 }
2189
2190 memset(&writes, 0, sizeof(writes));
2191
2192 writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
Chia-I Wu3dfc1342015-10-26 20:48:51 +08002193 writes[0].descriptorCount = 1;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002194 writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
Tony Barboura72d9492017-01-11 13:35:09 -07002195 writes[0].pBufferInfo = &buffer_info;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002196
2197 writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002198 writes[1].dstBinding = 1;
Chia-I Wu3dfc1342015-10-26 20:48:51 +08002199 writes[1].descriptorCount = DEMO_TEXTURE_COUNT;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002200 writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
Courtney Goeltzenleuchterc3ad65e2015-10-23 13:38:14 -06002201 writes[1].pImageInfo = tex_descs;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002202
Tony Barboura72d9492017-01-11 13:35:09 -07002203 for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
2204 err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->swapchain_image_resources[i].descriptor_set);
2205 assert(!err);
2206 buffer_info.buffer = demo->swapchain_image_resources[i].uniform_buffer;
2207 writes[0].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2208 writes[1].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2209 vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL);
2210 }
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002211}
2212
Karl Schultze4dc75c2016-02-02 15:37:51 -07002213static void demo_prepare_framebuffers(struct demo *demo) {
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06002214 VkImageView attachments[2];
Cody Northrop2e11cad2015-08-04 10:47:08 -06002215 attachments[1] = demo->depth.view;
2216
Chia-I Wuf973e322015-07-08 13:34:24 +08002217 const VkFramebufferCreateInfo fb_info = {
Karl Schultze4dc75c2016-02-02 15:37:51 -07002218 .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
2219 .pNext = NULL,
2220 .renderPass = demo->render_pass,
2221 .attachmentCount = 2,
2222 .pAttachments = attachments,
2223 .width = demo->width,
2224 .height = demo->height,
2225 .layers = 1,
Chia-I Wuf973e322015-07-08 13:34:24 +08002226 };
2227 VkResult U_ASSERT_ONLY err;
2228 uint32_t i;
2229
Tony Barbourd8e504f2015-10-08 14:26:24 -06002230 for (i = 0; i < demo->swapchainImageCount; i++) {
Tony Barboura72d9492017-01-11 13:35:09 -07002231 attachments[0] = demo->swapchain_image_resources[i].view;
Dave Houlton5fa47912018-02-16 11:02:26 -07002232 err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->swapchain_image_resources[i].framebuffer);
Chia-I Wuf973e322015-07-08 13:34:24 +08002233 assert(!err);
2234 }
2235}
2236
Karl Schultze4dc75c2016-02-02 15:37:51 -07002237static void demo_prepare(struct demo *demo) {
Joshua Ashton66d9c4c2021-06-17 19:05:16 +01002238 demo_prepare_buffers(demo);
2239
2240 if (demo->is_minimized) {
2241 demo->prepared = false;
2242 return;
2243 }
2244
Cody Northrop91e221b2015-07-09 18:08:32 -06002245 VkResult U_ASSERT_ONLY err;
Jeremy Kniager602e4182018-01-19 10:52:34 -07002246 if (demo->cmd_pool == VK_NULL_HANDLE) {
2247 const VkCommandPoolCreateInfo cmd_pool_info = {
2248 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2249 .pNext = NULL,
2250 .queueFamilyIndex = demo->graphics_queue_family_index,
2251 .flags = 0,
2252 };
2253 err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool);
2254 assert(!err);
2255 }
Cody Northrop91e221b2015-07-09 18:08:32 -06002256
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002257 const VkCommandBufferAllocateInfo cmd = {
Chia-I Wuf48700b2015-11-10 16:21:09 +08002258 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002259 .pNext = NULL,
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002260 .commandPool = demo->cmd_pool,
2261 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
Jon Ashburn0bec67e2016-01-11 13:12:43 -07002262 .commandBufferCount = 1,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002263 };
Tony Barbour6db4fcb2016-10-19 13:41:16 -06002264 err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->cmd);
2265 assert(!err);
2266 VkCommandBufferBeginInfo cmd_buf_info = {
2267 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2268 .pNext = NULL,
2269 .flags = 0,
2270 .pInheritanceInfo = NULL,
2271 };
2272 err = vkBeginCommandBuffer(demo->cmd, &cmd_buf_info);
2273 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002274
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002275 demo_prepare_depth(demo);
2276 demo_prepare_textures(demo);
Tony Barboura72d9492017-01-11 13:35:09 -07002277 demo_prepare_cube_data_buffers(demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002278
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002279 demo_prepare_descriptor_layout(demo);
Chia-I Wuf973e322015-07-08 13:34:24 +08002280 demo_prepare_render_pass(demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002281 demo_prepare_pipeline(demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002282
Ian Elliotta0781972015-08-21 15:09:33 -06002283 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002284 err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->swapchain_image_resources[i].cmd);
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002285 assert(!err);
2286 }
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002287
Tony Barbour22e06272016-09-07 16:07:56 -06002288 if (demo->separate_present_queue) {
Karl Schultza2615462017-01-20 13:19:20 -07002289 const VkCommandPoolCreateInfo present_cmd_pool_info = {
Tony Barbour22e06272016-09-07 16:07:56 -06002290 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2291 .pNext = NULL,
2292 .queueFamilyIndex = demo->present_queue_family_index,
2293 .flags = 0,
2294 };
Dave Houlton5fa47912018-02-16 11:02:26 -07002295 err = vkCreateCommandPool(demo->device, &present_cmd_pool_info, NULL, &demo->present_cmd_pool);
Tony Barbour22e06272016-09-07 16:07:56 -06002296 assert(!err);
Karl Schultza2615462017-01-20 13:19:20 -07002297 const VkCommandBufferAllocateInfo present_cmd_info = {
Tony Barbour22e06272016-09-07 16:07:56 -06002298 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
2299 .pNext = NULL,
2300 .commandPool = demo->present_cmd_pool,
2301 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
2302 .commandBufferCount = 1,
2303 };
2304 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002305 err = vkAllocateCommandBuffers(demo->device, &present_cmd_info,
2306 &demo->swapchain_image_resources[i].graphics_to_present_cmd);
Tony Barbour22e06272016-09-07 16:07:56 -06002307 assert(!err);
2308 demo_build_image_ownership_cmd(demo, i);
2309 }
2310 }
2311
Chia-I Wu63ea9262015-03-26 13:14:16 +08002312 demo_prepare_descriptor_pool(demo);
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002313 demo_prepare_descriptor_set(demo);
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002314
Chia-I Wuf973e322015-07-08 13:34:24 +08002315 demo_prepare_framebuffers(demo);
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002316
Ian Elliotta0781972015-08-21 15:09:33 -06002317 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002318 demo->current_buffer = i;
Tony Barboura72d9492017-01-11 13:35:09 -07002319 demo_draw_build_cmd(demo, demo->swapchain_image_resources[i].cmd);
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002320 }
2321
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -06002322 /*
2323 * Prepare functions above may generate pipeline commands
2324 * that need to be flushed before beginning the render loop.
2325 */
2326 demo_flush_init_cmd(demo);
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002327 if (demo->staging_texture.buffer) {
2328 demo_destroy_texture(demo, &demo->staging_texture);
Tony Barbour16156cb2016-10-19 14:15:49 -06002329 }
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -06002330
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002331 demo->current_buffer = 0;
Mike Stroyanbb60b382015-10-28 09:46:57 -06002332 demo->prepared = true;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002333}
2334
Karl Schultze4dc75c2016-02-02 15:37:51 -07002335static void demo_cleanup(struct demo *demo) {
David Pinedo2bb7c932015-06-18 17:03:14 -06002336 uint32_t i;
2337
2338 demo->prepared = false;
Tony Barbource7524e2016-07-28 12:01:45 -06002339 vkDeviceWaitIdle(demo->device);
David Pinedo2bb7c932015-06-18 17:03:14 -06002340
Tony Barbour66a56c32016-09-21 13:10:56 -06002341 // Wait for fences from present operations
2342 for (i = 0; i < FRAME_LAG; i++) {
szdarkhackd322ff02016-10-08 09:51:22 +03002343 vkWaitForFences(demo->device, 1, &demo->fences[i], VK_TRUE, UINT64_MAX);
Tony Barbour66a56c32016-09-21 13:10:56 -06002344 vkDestroyFence(demo->device, demo->fences[i], NULL);
2345 vkDestroySemaphore(demo->device, demo->image_acquired_semaphores[i], NULL);
2346 vkDestroySemaphore(demo->device, demo->draw_complete_semaphores[i], NULL);
2347 if (demo->separate_present_queue) {
2348 vkDestroySemaphore(demo->device, demo->image_ownership_semaphores[i], NULL);
2349 }
2350 }
2351
Jeremy Kniager602e4182018-01-19 10:52:34 -07002352 // If the window is currently minimized, demo_resize has already done some cleanup for us.
2353 if (!demo->is_minimized) {
2354 for (i = 0; i < demo->swapchainImageCount; i++) {
2355 vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
2356 }
2357 vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
Chia-I Wuf973e322015-07-08 13:34:24 +08002358
Jeremy Kniager602e4182018-01-19 10:52:34 -07002359 vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2360 vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2361 vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2362 vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2363 vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002364
Jeremy Kniager602e4182018-01-19 10:52:34 -07002365 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2366 vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2367 vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2368 vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2369 vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
2370 }
2371 demo->fpDestroySwapchainKHR(demo->device, demo->swapchain, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002372
Jeremy Kniager602e4182018-01-19 10:52:34 -07002373 vkDestroyImageView(demo->device, demo->depth.view, NULL);
2374 vkDestroyImage(demo->device, demo->depth.image, NULL);
2375 vkFreeMemory(demo->device, demo->depth.mem, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002376
Jeremy Kniager602e4182018-01-19 10:52:34 -07002377 for (i = 0; i < demo->swapchainImageCount; i++) {
2378 vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
2379 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
2380 vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002381 vkUnmapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory);
Jeremy Kniager602e4182018-01-19 10:52:34 -07002382 vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
2383 }
2384 free(demo->swapchain_image_resources);
2385 free(demo->queue_props);
2386 vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
Tony Barbour66a56c32016-09-21 13:10:56 -06002387
Jeremy Kniager602e4182018-01-19 10:52:34 -07002388 if (demo->separate_present_queue) {
2389 vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2390 }
Tony Barbour22e06272016-09-07 16:07:56 -06002391 }
Tony Barbourffa9a422016-11-10 16:45:15 -07002392 vkDeviceWaitIdle(demo->device);
Chia-I Wu63636062015-10-26 21:10:41 +08002393 vkDestroyDevice(demo->device, NULL);
Tony Barbourd70b42c2015-06-30 14:14:19 -06002394 if (demo->validate) {
Mark Young66510e52017-11-10 10:05:14 -07002395 demo->DestroyDebugUtilsMessengerEXT(demo->inst, demo->dbg_messenger, NULL);
Tony Barbourd70b42c2015-06-30 14:14:19 -06002396 }
Ian Elliottb08e0d92015-11-20 11:55:46 -07002397 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002398
Tony Barbour153cb062016-12-07 13:43:36 -07002399#if defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07002400 XDestroyWindow(demo->display, demo->xlib_window);
2401 XCloseDisplay(demo->display);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002402#elif defined(VK_USE_PLATFORM_XCB_KHR)
Pavol Klacansky573a19d2016-05-10 03:08:19 -06002403 xcb_destroy_window(demo->connection, demo->xcb_window);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002404 xcb_disconnect(demo->connection);
2405 free(demo->atom_wm_delete_window);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002406#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
shironeko689140c2022-05-19 10:21:07 -04002407 if (demo->keyboard) wl_keyboard_destroy(demo->keyboard);
2408 if (demo->pointer) wl_pointer_destroy(demo->pointer);
2409 if (demo->seat) wl_seat_destroy(demo->seat);
Manuel Stoecklac939332019-06-26 20:55:53 -04002410 xdg_toplevel_destroy(demo->xdg_toplevel);
2411 xdg_surface_destroy(demo->xdg_surface);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002412 wl_surface_destroy(demo->window);
Manuel Stoecklac939332019-06-26 20:55:53 -04002413 xdg_wm_base_destroy(demo->xdg_wm_base);
2414 if (demo->xdg_decoration_mgr) {
2415 zxdg_toplevel_decoration_v1_destroy(demo->toplevel_decoration);
2416 zxdg_decoration_manager_v1_destroy(demo->xdg_decoration_mgr);
2417 }
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002418 wl_compositor_destroy(demo->compositor);
2419 wl_registry_destroy(demo->registry);
2420 wl_display_disconnect(demo->display);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002421#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2422 demo->event_buffer->Release(demo->event_buffer);
2423 demo->window->Release(demo->window);
2424 demo->dfb->Release(demo->dfb);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002425#endif
Karl Schultz86429112017-06-20 11:27:59 -06002426
2427 vkDestroyInstance(demo->inst, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002428}
2429
Karl Schultze4dc75c2016-02-02 15:37:51 -07002430static void demo_resize(struct demo *demo) {
Ian Elliottcf074d32015-10-16 18:02:43 -06002431 uint32_t i;
2432
Mike Stroyanbb60b382015-10-28 09:46:57 -06002433 // Don't react to resize until after first initialization.
2434 if (!demo->prepared) {
Jeremy Kniager602e4182018-01-19 10:52:34 -07002435 if (demo->is_minimized) {
2436 demo_prepare(demo);
2437 }
Mike Stroyanbb60b382015-10-28 09:46:57 -06002438 return;
2439 }
Ian Elliottcf074d32015-10-16 18:02:43 -06002440 // In order to properly resize the window, we must re-create the swapchain
2441 // AND redo the command buffers, etc.
2442 //
2443 // First, perform part of the demo_cleanup() function:
2444 demo->prepared = false;
Tony Barbource7524e2016-07-28 12:01:45 -06002445 vkDeviceWaitIdle(demo->device);
Ian Elliottcf074d32015-10-16 18:02:43 -06002446
2447 for (i = 0; i < demo->swapchainImageCount; i++) {
Tony Barboura72d9492017-01-11 13:35:09 -07002448 vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002449 }
Chia-I Wu63636062015-10-26 21:10:41 +08002450 vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002451
Chia-I Wu63636062015-10-26 21:10:41 +08002452 vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2453 vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2454 vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2455 vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2456 vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002457
2458 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
Chia-I Wu63636062015-10-26 21:10:41 +08002459 vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2460 vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2461 vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2462 vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002463 }
Ian Elliottcf074d32015-10-16 18:02:43 -06002464
Chia-I Wu63636062015-10-26 21:10:41 +08002465 vkDestroyImageView(demo->device, demo->depth.view, NULL);
2466 vkDestroyImage(demo->device, demo->depth.image, NULL);
2467 vkFreeMemory(demo->device, demo->depth.mem, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002468
Ian Elliottcf074d32015-10-16 18:02:43 -06002469 for (i = 0; i < demo->swapchainImageCount; i++) {
Tony Barboura72d9492017-01-11 13:35:09 -07002470 vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
Dave Houlton5fa47912018-02-16 11:02:26 -07002471 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
Tony Barboura72d9492017-01-11 13:35:09 -07002472 vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002473 vkUnmapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory);
Tony Barboura72d9492017-01-11 13:35:09 -07002474 vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002475 }
Chia-I Wu63636062015-10-26 21:10:41 +08002476 vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
Jeremy Kniager602e4182018-01-19 10:52:34 -07002477 demo->cmd_pool = VK_NULL_HANDLE;
Tony Barbour22e06272016-09-07 16:07:56 -06002478 if (demo->separate_present_queue) {
2479 vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2480 }
Tony Barboura72d9492017-01-11 13:35:09 -07002481 free(demo->swapchain_image_resources);
Ian Elliottcf074d32015-10-16 18:02:43 -06002482
Ian Elliottcf074d32015-10-16 18:02:43 -06002483 // Second, re-perform the demo_prepare() function, which will re-create the
2484 // swapchain:
2485 demo_prepare(demo);
2486}
2487
David Pinedo2bb7c932015-06-18 17:03:14 -06002488// On MS-Windows, make this a global, so it's available to WndProc()
2489struct demo demo;
2490
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002491#if defined(VK_USE_PLATFORM_WIN32_KHR)
Karl Schultze4dc75c2016-02-02 15:37:51 -07002492static void demo_run(struct demo *demo) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002493 if (!demo->prepared) return;
Tony Barbource7524e2016-07-28 12:01:45 -06002494
Ian Elliott639ca472015-04-16 15:23:05 -06002495 demo_draw(demo);
David Pinedo2bb7c932015-06-18 17:03:14 -06002496 demo->curFrame++;
Petr Krausd88e4e52019-01-23 18:45:04 +01002497 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
Karl Schultz8a663912016-03-24 18:43:41 -06002498 PostQuitMessage(validation_error);
David Pinedo2bb7c932015-06-18 17:03:14 -06002499 }
David Pinedo2bb7c932015-06-18 17:03:14 -06002500}
Ian Elliott639ca472015-04-16 15:23:05 -06002501
2502// MS-Windows event handling function:
Karl Schultze4dc75c2016-02-02 15:37:51 -07002503LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2504 switch (uMsg) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002505 case WM_CLOSE:
2506 PostQuitMessage(validation_error);
2507 break;
2508 case WM_PAINT:
2509 // The validation callback calls MessageBox which can generate paint
2510 // events - don't make more Vulkan calls if we got here from the
2511 // callback
2512 if (!in_callback) {
2513 demo_run(&demo);
2514 }
2515 break;
2516 case WM_GETMINMAXINFO: // set window's minimum size
2517 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2518 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002519 case WM_ERASEBKGND:
2520 return 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07002521 case WM_SIZE:
2522 // Resize the application to the new window size, except when
2523 // it was minimized. Vulkan doesn't support images or swapchains
2524 // with width=0 and height=0.
2525 if (wParam != SIZE_MINIMIZED) {
2526 demo.width = lParam & 0xffff;
2527 demo.height = (lParam & 0xffff0000) >> 16;
2528 demo_resize(&demo);
2529 }
2530 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002531 case WM_KEYDOWN:
2532 switch (wParam) {
2533 case VK_ESCAPE:
2534 PostQuitMessage(validation_error);
2535 break;
2536 case VK_LEFT:
2537 demo.spin_angle -= demo.spin_increment;
2538 break;
2539 case VK_RIGHT:
2540 demo.spin_angle += demo.spin_increment;
2541 break;
2542 case VK_SPACE:
2543 demo.pause = !demo.pause;
2544 break;
2545 }
2546 return 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07002547 default:
2548 break;
Ian Elliott639ca472015-04-16 15:23:05 -06002549 }
2550 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2551}
2552
Karl Schultze4dc75c2016-02-02 15:37:51 -07002553static void demo_create_window(struct demo *demo) {
2554 WNDCLASSEX win_class;
Ian Elliott639ca472015-04-16 15:23:05 -06002555
2556 // Initialize the window class structure:
2557 win_class.cbSize = sizeof(WNDCLASSEX);
2558 win_class.style = CS_HREDRAW | CS_VREDRAW;
2559 win_class.lpfnWndProc = WndProc;
2560 win_class.cbClsExtra = 0;
2561 win_class.cbWndExtra = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07002562 win_class.hInstance = demo->connection; // hInstance
Ian Elliott639ca472015-04-16 15:23:05 -06002563 win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
2564 win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
2565 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2566 win_class.lpszMenuName = NULL;
2567 win_class.lpszClassName = demo->name;
2568 win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
2569 // Register window class:
2570 if (!RegisterClassEx(&win_class)) {
2571 // It didn't work, so try to give a useful error:
2572 printf("Unexpected error trying to start the application!\n");
2573 fflush(stdout);
2574 exit(1);
2575 }
2576 // Create window with the registered class:
Karl Schultze4dc75c2016-02-02 15:37:51 -07002577 RECT wr = {0, 0, demo->width, demo->height};
Mike Stroyanb46779e2015-06-15 14:20:13 -06002578 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
Ian Elliott639ca472015-04-16 15:23:05 -06002579 demo->window = CreateWindowEx(0,
Dave Houlton5fa47912018-02-16 11:02:26 -07002580 demo->name, // class name
2581 demo->name, // app name
2582 WS_OVERLAPPEDWINDOW | // window style
Karl Schultze4dc75c2016-02-02 15:37:51 -07002583 WS_VISIBLE | WS_SYSMENU,
Dave Houlton5fa47912018-02-16 11:02:26 -07002584 100, 100, // x/y coords
2585 wr.right - wr.left, // width
2586 wr.bottom - wr.top, // height
2587 NULL, // handle to parent
2588 NULL, // handle to menu
2589 demo->connection, // hInstance
2590 NULL); // no extra parameters
Ian Elliott639ca472015-04-16 15:23:05 -06002591 if (!demo->window) {
2592 // It didn't work, so try to give a useful error:
2593 printf("Cannot create a window in which to draw!\n");
2594 fflush(stdout);
2595 exit(1);
2596 }
Rene Lindsayb9403da2016-07-01 18:00:30 -06002597 // Window client area size must be at least 1 pixel high, to prevent crash.
2598 demo->minsize.x = GetSystemMetrics(SM_CXMINTRACK);
Dave Houlton5fa47912018-02-16 11:02:26 -07002599 demo->minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
Ian Elliott639ca472015-04-16 15:23:05 -06002600}
Tony Barbour8295ac42016-08-08 11:04:17 -06002601#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour2593b182016-04-19 10:57:58 -06002602static void demo_create_xlib_window(struct demo *demo) {
Mike Weiblen5d2ad542018-02-13 13:56:13 -07002603 const char *display_envar = getenv("DISPLAY");
2604 if (display_envar == NULL || display_envar[0] == '\0') {
2605 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2606 fflush(stdout);
2607 exit(1);
2608 }
Tony Barbour2593b182016-04-19 10:57:58 -06002609
Tony Barbouree9cd372017-01-31 16:09:58 -07002610 XInitThreads();
Tony Barbour2593b182016-04-19 10:57:58 -06002611 demo->display = XOpenDisplay(NULL);
2612 long visualMask = VisualScreenMask;
2613 int numberOfVisuals;
Dave Houlton5fa47912018-02-16 11:02:26 -07002614 XVisualInfo vInfoTemplate = {};
Tony Barbour2593b182016-04-19 10:57:58 -06002615 vInfoTemplate.screen = DefaultScreen(demo->display);
Dave Houlton5fa47912018-02-16 11:02:26 -07002616 XVisualInfo *visualInfo = XGetVisualInfo(demo->display, visualMask, &vInfoTemplate, &numberOfVisuals);
Tony Barbour2593b182016-04-19 10:57:58 -06002617
Dave Houlton5fa47912018-02-16 11:02:26 -07002618 Colormap colormap =
2619 XCreateColormap(demo->display, RootWindow(demo->display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
Tony Barbour2593b182016-04-19 10:57:58 -06002620
Dave Houlton5fa47912018-02-16 11:02:26 -07002621 XSetWindowAttributes windowAttributes = {};
Tony Barbour2593b182016-04-19 10:57:58 -06002622 windowAttributes.colormap = colormap;
2623 windowAttributes.background_pixel = 0xFFFFFFFF;
2624 windowAttributes.border_pixel = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07002625 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
Tony Barbour2593b182016-04-19 10:57:58 -06002626
Dave Houlton5fa47912018-02-16 11:02:26 -07002627 demo->xlib_window = XCreateWindow(demo->display, RootWindow(demo->display, vInfoTemplate.screen), 0, 0, demo->width,
2628 demo->height, 0, visualInfo->depth, InputOutput, visualInfo->visual,
2629 CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
Tony Barbour2593b182016-04-19 10:57:58 -06002630
2631 XSelectInput(demo->display, demo->xlib_window, ExposureMask | KeyPressMask);
2632 XMapWindow(demo->display, demo->xlib_window);
2633 XFlush(demo->display);
Dave Houlton5fa47912018-02-16 11:02:26 -07002634 demo->xlib_wm_delete_window = XInternAtom(demo->display, "WM_DELETE_WINDOW", False);
Tony Barbour2593b182016-04-19 10:57:58 -06002635}
2636static void demo_handle_xlib_event(struct demo *demo, const XEvent *event) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002637 switch (event->type) {
2638 case ClientMessage:
2639 if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window) demo->quit = true;
Tony Barbour2593b182016-04-19 10:57:58 -06002640 break;
Dave Houlton5fa47912018-02-16 11:02:26 -07002641 case KeyPress:
2642 switch (event->xkey.keycode) {
2643 case 0x9: // Escape
2644 demo->quit = true;
2645 break;
2646 case 0x71: // left arrow key
2647 demo->spin_angle -= demo->spin_increment;
2648 break;
2649 case 0x72: // right arrow key
2650 demo->spin_angle += demo->spin_increment;
2651 break;
2652 case 0x41: // space bar
2653 demo->pause = !demo->pause;
2654 break;
2655 }
Tony Barbour2593b182016-04-19 10:57:58 -06002656 break;
Dave Houlton5fa47912018-02-16 11:02:26 -07002657 case ConfigureNotify:
2658 if ((demo->width != event->xconfigure.width) || (demo->height != event->xconfigure.height)) {
2659 demo->width = event->xconfigure.width;
2660 demo->height = event->xconfigure.height;
2661 demo_resize(demo);
2662 }
Karl Schultz6ddf1e02017-01-04 10:31:20 -07002663 break;
Dave Houlton5fa47912018-02-16 11:02:26 -07002664 default:
Tony Barbour2593b182016-04-19 10:57:58 -06002665 break;
Tony Barbour2593b182016-04-19 10:57:58 -06002666 }
Tony Barbour2593b182016-04-19 10:57:58 -06002667}
2668
2669static void demo_run_xlib(struct demo *demo) {
Tony Barbour2593b182016-04-19 10:57:58 -06002670 while (!demo->quit) {
2671 XEvent event;
2672
2673 if (demo->pause) {
2674 XNextEvent(demo->display, &event);
2675 demo_handle_xlib_event(demo, &event);
Karl Schultz6ddf1e02017-01-04 10:31:20 -07002676 }
2677 while (XPending(demo->display) > 0) {
2678 XNextEvent(demo->display, &event);
2679 demo_handle_xlib_event(demo, &event);
Tony Barbour2593b182016-04-19 10:57:58 -06002680 }
2681
Tony Barbour2593b182016-04-19 10:57:58 -06002682 demo_draw(demo);
Tony Barbour2593b182016-04-19 10:57:58 -06002683 demo->curFrame++;
Dave Houlton5fa47912018-02-16 11:02:26 -07002684 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
Tony Barbour2593b182016-04-19 10:57:58 -06002685 }
2686}
Tony Barbour153cb062016-12-07 13:43:36 -07002687#elif defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002688static void demo_handle_xcb_event(struct demo *demo, const xcb_generic_event_t *event) {
Piers Daniell735ee532015-02-23 16:23:13 -07002689 uint8_t event_code = event->response_type & 0x7f;
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002690 switch (event_code) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002691 case XCB_EXPOSE:
2692 // TODO: Resize window
2693 break;
2694 case XCB_CLIENT_MESSAGE:
2695 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*demo->atom_wm_delete_window).atom) {
2696 demo->quit = true;
2697 }
2698 break;
2699 case XCB_KEY_RELEASE: {
2700 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002701
Dave Houlton5fa47912018-02-16 11:02:26 -07002702 switch (key->detail) {
2703 case 0x9: // Escape
2704 demo->quit = true;
2705 break;
2706 case 0x71: // left arrow key
2707 demo->spin_angle -= demo->spin_increment;
2708 break;
2709 case 0x72: // right arrow key
2710 demo->spin_angle += demo->spin_increment;
2711 break;
2712 case 0x41: // space bar
2713 demo->pause = !demo->pause;
2714 break;
2715 }
2716 } break;
2717 case XCB_CONFIGURE_NOTIFY: {
2718 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2719 if ((demo->width != cfg->width) || (demo->height != cfg->height)) {
2720 demo->width = cfg->width;
2721 demo->height = cfg->height;
2722 demo_resize(demo);
2723 }
2724 } break;
2725 default:
Karl Schultze4dc75c2016-02-02 15:37:51 -07002726 break;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002727 }
2728}
2729
Tony Barbour2593b182016-04-19 10:57:58 -06002730static void demo_run_xcb(struct demo *demo) {
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002731 xcb_flush(demo->connection);
2732
2733 while (!demo->quit) {
2734 xcb_generic_event_t *event;
2735
Courtney Goeltzenleuchterc465d6c2014-11-18 11:28:09 -07002736 if (demo->pause) {
2737 event = xcb_wait_for_event(demo->connection);
Dave Houlton5fa47912018-02-16 11:02:26 -07002738 } else {
Courtney Goeltzenleuchterc465d6c2014-11-18 11:28:09 -07002739 event = xcb_poll_for_event(demo->connection);
Karl Schultz6ddf1e02017-01-04 10:31:20 -07002740 }
2741 while (event) {
2742 demo_handle_xcb_event(demo, event);
2743 free(event);
2744 event = xcb_poll_for_event(demo->connection);
Courtney Goeltzenleuchter98085552014-11-10 11:13:13 -07002745 }
Courtney Goeltzenleuchterc465d6c2014-11-18 11:28:09 -07002746
Courtney Goeltzenleuchter98085552014-11-10 11:13:13 -07002747 demo_draw(demo);
David Pinedo2bb7c932015-06-18 17:03:14 -06002748 demo->curFrame++;
Dave Houlton5fa47912018-02-16 11:02:26 -07002749 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002750 }
2751}
2752
Tony Barbour2593b182016-04-19 10:57:58 -06002753static void demo_create_xcb_window(struct demo *demo) {
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002754 uint32_t value_mask, value_list[32];
2755
Tony Barbour2593b182016-04-19 10:57:58 -06002756 demo->xcb_window = xcb_generate_id(demo->connection);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002757
2758 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2759 value_list[0] = demo->screen->black_pixel;
Dave Houlton5fa47912018-02-16 11:02:26 -07002760 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002761
Dave Houlton5fa47912018-02-16 11:02:26 -07002762 xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window, demo->screen->root, 0, 0, demo->width, demo->height,
2763 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, value_mask, value_list);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002764
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002765 /* Magic code that will send notification when window is destroyed */
Dave Houlton5fa47912018-02-16 11:02:26 -07002766 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS");
2767 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(demo->connection, cookie, 0);
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002768
Dave Houlton5fa47912018-02-16 11:02:26 -07002769 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW");
2770 demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0);
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002771
Dave Houlton5fa47912018-02-16 11:02:26 -07002772 xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window, (*reply).atom, 4, 32, 1,
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002773 &(*demo->atom_wm_delete_window).atom);
2774 free(reply);
2775
Tony Barbour2593b182016-04-19 10:57:58 -06002776 xcb_map_window(demo->connection, demo->xcb_window);
David Pinedo2bb7c932015-06-18 17:03:14 -06002777
Karl Schultze4dc75c2016-02-02 15:37:51 -07002778 // Force the x/y coordinates to 100,100 results are identical in consecutive
2779 // runs
2780 const uint32_t coords[] = {100, 100};
Dave Houlton5fa47912018-02-16 11:02:26 -07002781 xcb_configure_window(demo->connection, demo->xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002782}
Tony Barbour6b131662016-08-25 13:14:45 -06002783// VK_USE_PLATFORM_XCB_KHR
2784#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002785static void demo_run(struct demo *demo) {
2786 while (!demo->quit) {
Joey Bzdek15eb0702017-06-07 09:40:36 -06002787 if (demo->pause) {
2788 wl_display_dispatch(demo->display); // block and wait for input
Joey Bzdek33bc5c82017-06-14 10:33:36 -06002789 } else {
Joey Bzdek15eb0702017-06-07 09:40:36 -06002790 wl_display_dispatch_pending(demo->display); // don't block
2791 demo_draw(demo);
2792 demo->curFrame++;
2793 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2794 }
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002795 }
2796}
2797
Manuel Stoecklac939332019-06-26 20:55:53 -04002798static void handle_surface_configure(void *data, struct xdg_surface *xdg_surface, uint32_t serial) {
2799 struct demo *demo = (struct demo *)data;
2800 xdg_surface_ack_configure(xdg_surface, serial);
2801 if (demo->xdg_surface_has_been_configured) {
2802 demo_resize(demo);
2803 }
2804 demo->xdg_surface_has_been_configured = 1;
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002805}
2806
Manuel Stoecklac939332019-06-26 20:55:53 -04002807static const struct xdg_surface_listener xdg_surface_listener = {handle_surface_configure};
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002808
Manuel Stoecklac939332019-06-26 20:55:53 -04002809static void handle_toplevel_configure(void *data, struct xdg_toplevel *xdg_toplevel UNUSED, int32_t width, int32_t height,
2810 struct wl_array *states UNUSED) {
2811 struct demo *demo = (struct demo *)data;
2812 /* zero values imply the program may choose its own size, so in that case
2813 * stay with the existing value (which on startup is the default) */
2814 if (width > 0) {
2815 demo->width = width;
2816 }
2817 if (height > 0) {
2818 demo->height = height;
2819 }
2820 /* This should be followed by a surface configure */
2821}
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002822
Manuel Stoecklac939332019-06-26 20:55:53 -04002823static void handle_toplevel_close(void *data, struct xdg_toplevel *xdg_toplevel UNUSED) {
2824 struct demo *demo = (struct demo *)data;
2825 demo->quit = true;
2826}
2827
2828static const struct xdg_toplevel_listener xdg_toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002829
2830static void demo_create_window(struct demo *demo) {
Manuel Stoecklac939332019-06-26 20:55:53 -04002831 if (!demo->xdg_wm_base) {
2832 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2833 fflush(stdout);
2834 exit(1);
2835 }
2836
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002837 demo->window = wl_compositor_create_surface(demo->compositor);
2838 if (!demo->window) {
2839 printf("Can not create wayland_surface from compositor!\n");
2840 fflush(stdout);
2841 exit(1);
2842 }
2843
Manuel Stoecklac939332019-06-26 20:55:53 -04002844 demo->xdg_surface = xdg_wm_base_get_xdg_surface(demo->xdg_wm_base, demo->window);
2845 if (!demo->xdg_surface) {
2846 printf("Can not get xdg_surface from wayland_surface!\n");
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002847 fflush(stdout);
2848 exit(1);
2849 }
Manuel Stoecklac939332019-06-26 20:55:53 -04002850 demo->xdg_toplevel = xdg_surface_get_toplevel(demo->xdg_surface);
2851 if (!demo->xdg_toplevel) {
2852 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2853 fflush(stdout);
2854 exit(1);
2855 }
2856 xdg_surface_add_listener(demo->xdg_surface, &xdg_surface_listener, demo);
2857 xdg_toplevel_add_listener(demo->xdg_toplevel, &xdg_toplevel_listener, demo);
2858 xdg_toplevel_set_title(demo->xdg_toplevel, APP_SHORT_NAME);
2859 if (demo->xdg_decoration_mgr) {
2860 // if supported, let the compositor render titlebars for us
2861 demo->toplevel_decoration =
2862 zxdg_decoration_manager_v1_get_toplevel_decoration(demo->xdg_decoration_mgr, demo->xdg_toplevel);
2863 zxdg_toplevel_decoration_v1_set_mode(demo->toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2864 }
2865
2866 wl_surface_commit(demo->window);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002867}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002868#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2869static void demo_create_directfb_window(struct demo *demo) {
2870 DFBResult ret;
2871
2872 ret = DirectFBInit(NULL, NULL);
2873 if (ret) {
2874 printf("DirectFBInit failed to initialize DirectFB!\n");
2875 fflush(stdout);
2876 exit(1);
2877 }
2878
2879 ret = DirectFBCreate(&demo->dfb);
2880 if (ret) {
2881 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2882 fflush(stdout);
2883 exit(1);
2884 }
2885
2886 DFBSurfaceDescription desc;
2887 desc.flags = DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT;
2888 desc.caps = DSCAPS_PRIMARY;
2889 desc.width = demo->width;
2890 desc.height = demo->height;
2891 ret = demo->dfb->CreateSurface(demo->dfb, &desc, &demo->window);
2892 if (ret) {
2893 printf("CreateSurface failed to create DirectFB surface interface!\n");
2894 fflush(stdout);
2895 exit(1);
2896 }
2897
2898 ret = demo->dfb->CreateInputEventBuffer(demo->dfb, DICAPS_KEYS, DFB_FALSE, &demo->event_buffer);
2899 if (ret) {
2900 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2901 fflush(stdout);
2902 exit(1);
2903 }
2904}
2905
2906static void demo_handle_directfb_event(struct demo *demo, const DFBInputEvent *event) {
2907 if (event->type != DIET_KEYPRESS) return;
2908 switch (event->key_symbol) {
2909 case DIKS_ESCAPE: // Escape
2910 demo->quit = true;
2911 break;
2912 case DIKS_CURSOR_LEFT: // left arrow key
2913 demo->spin_angle -= demo->spin_increment;
2914 break;
2915 case DIKS_CURSOR_RIGHT: // right arrow key
2916 demo->spin_angle += demo->spin_increment;
2917 break;
2918 case DIKS_SPACE: // space bar
2919 demo->pause = !demo->pause;
2920 break;
2921 default:
2922 break;
2923 }
2924}
2925
2926static void demo_run_directfb(struct demo *demo) {
2927 while (!demo->quit) {
2928 DFBInputEvent event;
2929
2930 if (demo->pause) {
2931 demo->event_buffer->WaitForEvent(demo->event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002932 if (!demo->event_buffer->GetEvent(demo->event_buffer, DFB_EVENT(&event))) demo_handle_directfb_event(demo, &event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002933 } else {
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002934 if (!demo->event_buffer->GetEvent(demo->event_buffer, DFB_EVENT(&event))) demo_handle_directfb_event(demo, &event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002935
2936 demo_draw(demo);
2937 demo->curFrame++;
2938 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2939 }
2940 }
2941}
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002942#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
2943static void demo_run(struct demo *demo) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002944 if (!demo->prepared) return;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002945
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002946 demo_draw(demo);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002947 demo->curFrame++;
2948}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002949#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002950static void demo_run(struct demo *demo) {
2951 demo_draw(demo);
2952 demo->curFrame++;
2953 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2954 demo->quit = TRUE;
2955 }
2956}
Damien Leone600c3052017-01-31 10:26:07 -07002957#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2958static VkResult demo_create_display_surface(struct demo *demo) {
2959 VkResult U_ASSERT_ONLY err;
2960 uint32_t display_count;
2961 uint32_t mode_count;
2962 uint32_t plane_count;
2963 VkDisplayPropertiesKHR display_props;
2964 VkDisplayKHR display;
2965 VkDisplayModePropertiesKHR mode_props;
2966 VkDisplayPlanePropertiesKHR *plane_props;
2967 VkBool32 found_plane = VK_FALSE;
2968 uint32_t plane_index;
2969 VkExtent2D image_extent;
2970 VkDisplaySurfaceCreateInfoKHR create_info;
2971
2972 // Get the first display
Damien Leone600c3052017-01-31 10:26:07 -07002973 display_count = 1;
2974 err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, &display_props);
2975 assert(!err || (err == VK_INCOMPLETE));
2976
2977 display = display_props.display;
2978
2979 // Get the first mode of the display
2980 err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, NULL);
2981 assert(!err);
2982
2983 if (mode_count == 0) {
2984 printf("Cannot find any mode for the display!\n");
2985 fflush(stdout);
2986 exit(1);
2987 }
2988
2989 mode_count = 1;
2990 err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, &mode_props);
2991 assert(!err || (err == VK_INCOMPLETE));
2992
2993 // Get the list of planes
2994 err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, NULL);
2995 assert(!err);
2996
2997 if (plane_count == 0) {
2998 printf("Cannot find any plane!\n");
2999 fflush(stdout);
3000 exit(1);
3001 }
3002
3003 plane_props = malloc(sizeof(VkDisplayPlanePropertiesKHR) * plane_count);
3004 assert(plane_props);
3005
3006 err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, plane_props);
3007 assert(!err);
3008
3009 // Find a plane compatible with the display
3010 for (plane_index = 0; plane_index < plane_count; plane_index++) {
3011 uint32_t supported_count;
3012 VkDisplayKHR *supported_displays;
3013
3014 // Disqualify planes that are bound to a different display
Dave Houlton5fa47912018-02-16 11:02:26 -07003015 if ((plane_props[plane_index].currentDisplay != VK_NULL_HANDLE) && (plane_props[plane_index].currentDisplay != display)) {
Damien Leone600c3052017-01-31 10:26:07 -07003016 continue;
3017 }
3018
3019 err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, NULL);
3020 assert(!err);
3021
3022 if (supported_count == 0) {
3023 continue;
3024 }
3025
3026 supported_displays = malloc(sizeof(VkDisplayKHR) * supported_count);
3027 assert(supported_displays);
3028
3029 err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, supported_displays);
3030 assert(!err);
3031
3032 for (uint32_t i = 0; i < supported_count; i++) {
3033 if (supported_displays[i] == display) {
3034 found_plane = VK_TRUE;
3035 break;
3036 }
3037 }
3038
3039 free(supported_displays);
3040
3041 if (found_plane) {
3042 break;
3043 }
3044 }
3045
3046 if (!found_plane) {
3047 printf("Cannot find a plane compatible with the display!\n");
3048 fflush(stdout);
3049 exit(1);
3050 }
3051
3052 free(plane_props);
3053
Tony Barbour820b55b2017-03-14 08:55:46 -06003054 VkDisplayPlaneCapabilitiesKHR planeCaps;
3055 vkGetDisplayPlaneCapabilitiesKHR(demo->gpu, mode_props.displayMode, plane_index, &planeCaps);
3056 // Find a supported alpha mode
Tony-LunarG02897e92021-06-15 13:14:06 -06003057 VkDisplayPlaneAlphaFlagBitsKHR alphaMode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR;
3058 VkDisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
Tony Barbour820b55b2017-03-14 08:55:46 -06003059 VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR,
3060 VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR,
3061 VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR,
3062 VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR,
3063 };
3064 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
3065 if (planeCaps.supportedAlpha & alphaModes[i]) {
3066 alphaMode = alphaModes[i];
3067 break;
3068 }
3069 }
Damien Leone600c3052017-01-31 10:26:07 -07003070 image_extent.width = mode_props.parameters.visibleRegion.width;
3071 image_extent.height = mode_props.parameters.visibleRegion.height;
3072
3073 create_info.sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR;
3074 create_info.pNext = NULL;
3075 create_info.flags = 0;
3076 create_info.displayMode = mode_props.displayMode;
3077 create_info.planeIndex = plane_index;
3078 create_info.planeStackIndex = plane_props[plane_index].currentStackIndex;
3079 create_info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Tony Barbour820b55b2017-03-14 08:55:46 -06003080 create_info.alphaMode = alphaMode;
Damien Leone600c3052017-01-31 10:26:07 -07003081 create_info.globalAlpha = 1.0f;
3082 create_info.imageExtent = image_extent;
3083
3084 return vkCreateDisplayPlaneSurfaceKHR(demo->inst, &create_info, NULL, &demo->surface);
3085}
3086
Dave Houlton5fa47912018-02-16 11:02:26 -07003087static void demo_run_display(struct demo *demo) {
Damien Leone600c3052017-01-31 10:26:07 -07003088 while (!demo->quit) {
3089 demo_draw(demo);
3090 demo->curFrame++;
3091
3092 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
3093 demo->quit = true;
3094 }
3095 }
3096}
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003097#endif
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003098
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003099/*
3100 * Return 1 (true) if all layer names specified in check_names
3101 * can be found in given layer properties.
3102 */
Dave Houlton5fa47912018-02-16 11:02:26 -07003103static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, uint32_t layer_count, VkLayerProperties *layers) {
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003104 for (uint32_t i = 0; i < check_count; i++) {
Courtney Goeltzenleuchterc88ce512015-07-09 11:44:38 -06003105 VkBool32 found = 0;
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003106 for (uint32_t j = 0; j < layer_count; j++) {
3107 if (!strcmp(check_names[i], layers[j].layerName)) {
3108 found = 1;
Dustin Graves7c287352016-01-27 13:48:06 -07003109 break;
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003110 }
3111 }
3112 if (!found) {
3113 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
3114 return 0;
3115 }
3116 }
3117 return 1;
3118}
Tony-LunarG27c21242021-03-11 16:28:19 -07003119#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
3120int find_display_gpu(int gpu_number, uint32_t gpu_count, VkPhysicalDevice *physical_devices) {
3121 uint32_t display_count = 0;
3122 VkResult result;
3123 int gpu_return = gpu_number;
3124 if (gpu_number >= 0) {
3125 result = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_devices[gpu_number], &display_count, NULL);
3126 assert(!result);
3127 } else {
3128 for (uint32_t i = 0; i < gpu_count; i++) {
3129 result = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_devices[i], &display_count, NULL);
3130 assert(!result);
3131 if (display_count) {
3132 gpu_return = i;
3133 break;
3134 }
3135 }
3136 }
3137 if (display_count > 0)
3138 return gpu_return;
3139 else
3140 return -1;
3141}
3142#endif
Karl Schultze4dc75c2016-02-02 15:37:51 -07003143static void demo_init_vk(struct demo *demo) {
Tobin Ehlis99239dc2015-04-16 18:04:57 -06003144 VkResult err;
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -06003145 uint32_t instance_extension_count = 0;
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003146 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06003147 char *instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Karl Schultz7c50ad62016-04-01 12:07:03 -06003148 demo->enabled_extension_count = 0;
3149 demo->enabled_layer_count = 0;
Jeremy Kniager602e4182018-01-19 10:52:34 -07003150 demo->is_minimized = false;
3151 demo->cmd_pool = VK_NULL_HANDLE;
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003152
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06003153 // Look for validation layers
Courtney Goeltzenleuchterc88ce512015-07-09 11:44:38 -06003154 VkBool32 validation_found = 0;
Karl Schultz7c50ad62016-04-01 12:07:03 -06003155 if (demo->validate) {
Karl Schultz7c50ad62016-04-01 12:07:03 -06003156 err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
Dustin Graves7c287352016-01-27 13:48:06 -07003157 assert(!err);
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003158
Karl Schultz7c50ad62016-04-01 12:07:03 -06003159 if (instance_layer_count > 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003160 VkLayerProperties *instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count);
3161 err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers);
Karl Schultz7c50ad62016-04-01 12:07:03 -06003162 assert(!err);
Dustin Graves7c287352016-01-27 13:48:06 -07003163
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06003164 validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07003165 instance_layer_count, instance_layers);
Karl Schultz7c50ad62016-04-01 12:07:03 -06003166 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06003167 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
3168 demo->enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Karl Schultz7c50ad62016-04-01 12:07:03 -06003169 }
3170 free(instance_layers);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003171 }
Dustin Graves7c287352016-01-27 13:48:06 -07003172
Karl Schultz7c50ad62016-04-01 12:07:03 -06003173 if (!validation_found) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003174 ERR_EXIT(
3175 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
3176 "Please look at the Getting Started guide for additional information.\n",
3177 "vkCreateInstance Failure");
Karl Schultz7c50ad62016-04-01 12:07:03 -06003178 }
Dustin Graves7c287352016-01-27 13:48:06 -07003179 }
3180
3181 /* Look for instance extensions */
3182 VkBool32 surfaceExtFound = 0;
3183 VkBool32 platformSurfaceExtFound = 0;
Charles Giessen5f3ce242022-04-11 14:39:06 -06003184 bool portabilityEnumerationActive = false;
Karl Schultz7c50ad62016-04-01 12:07:03 -06003185 memset(demo->extension_names, 0, sizeof(demo->extension_names));
Dustin Graves7c287352016-01-27 13:48:06 -07003186
Dave Houlton5fa47912018-02-16 11:02:26 -07003187 err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003188 assert(!err);
3189
Dustin Graves7c287352016-01-27 13:48:06 -07003190 if (instance_extension_count > 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003191 VkExtensionProperties *instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count);
3192 err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions);
Dustin Graves7c287352016-01-27 13:48:06 -07003193 assert(!err);
3194 for (uint32_t i = 0; i < instance_extension_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003195 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Dustin Graves7c287352016-01-27 13:48:06 -07003196 surfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003197 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003198 }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003199#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003200 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Dustin Graves7c287352016-01-27 13:48:06 -07003201 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003202 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
Dustin Graves7c287352016-01-27 13:48:06 -07003203 }
Tony Barbour153cb062016-12-07 13:43:36 -07003204#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003205 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Tony Barbour2593b182016-04-19 10:57:58 -06003206 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003207 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
Tony Barbour2593b182016-04-19 10:57:58 -06003208 }
Tony Barbour153cb062016-12-07 13:43:36 -07003209#elif defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003210 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Dustin Graves7c287352016-01-27 13:48:06 -07003211 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003212 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
Dustin Graves7c287352016-01-27 13:48:06 -07003213 }
Tony Barbour153cb062016-12-07 13:43:36 -07003214#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003215 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003216 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003217 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003218 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003219#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3220 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3221 platformSurfaceExtFound = 1;
3222 demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
3223 }
Damien Leone600c3052017-01-31 10:26:07 -07003224#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003225 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Damien Leone600c3052017-01-31 10:26:07 -07003226 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003227 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
Damien Leone600c3052017-01-31 10:26:07 -07003228 }
Tony Barbour153cb062016-12-07 13:43:36 -07003229#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003230 if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003231 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003232 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003233 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04003234#elif defined(VK_USE_PLATFORM_METAL_EXT)
3235 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Bill Hollingsf4352142017-02-14 22:58:56 -05003236 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04003237 demo->extension_names[demo->enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Bill Hollingsf4352142017-02-14 22:58:56 -05003238 }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003239#endif
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05003240 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3241 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
3242 }
Mark Young66510e52017-11-10 10:05:14 -07003243 if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3244 if (demo->validate) {
3245 demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
3246 }
3247 }
Charles Giessen5f3ce242022-04-11 14:39:06 -06003248 // We want cube to be able to enumerate drivers that support the portability_subset extension, so we have to enable the
3249 // portability enumeration extension.
3250 if (!strcmp(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3251 portabilityEnumerationActive = true;
3252 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME;
3253 }
Karl Schultz7c50ad62016-04-01 12:07:03 -06003254 assert(demo->enabled_extension_count < 64);
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -06003255 }
Dustin Graves7c287352016-01-27 13:48:06 -07003256
3257 free(instance_extensions);
Tobin Ehlis99239dc2015-04-16 18:04:57 -06003258 }
Dustin Graves7c287352016-01-27 13:48:06 -07003259
Ian Elliottd3f7dcc2015-11-20 13:08:34 -07003260 if (!surfaceExtFound) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003261 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
3262 " extension.\n\n"
3263 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3264 "Please look at the Getting Started guide for additional information.\n",
Ian Elliott65152912015-04-28 13:22:33 -06003265 "vkCreateInstance Failure");
3266 }
Ian Elliottd3f7dcc2015-11-20 13:08:34 -07003267 if (!platformSurfaceExtFound) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003268#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003269 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
3270 " extension.\n\n"
3271 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3272 "Please look at the Getting Started guide for additional information.\n",
Ian Elliottd3f7dcc2015-11-20 13:08:34 -07003273 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04003274#elif defined(VK_USE_PLATFORM_METAL_EXT)
3275 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Dave Houlton5fa47912018-02-16 11:02:26 -07003276 " extension.\n\n"
3277 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3278 "Please look at the Getting Started guide for additional information.\n",
Tony Barbourc65cd752017-03-13 15:29:35 -06003279 "vkCreateInstance Failure");
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003280#elif defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003281 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
3282 " extension.\n\n"
3283 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3284 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski6f7a6032015-11-24 12:04:15 -07003285 "vkCreateInstance Failure");
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003286#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003287 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
3288 " extension.\n\n"
3289 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3290 "Please look at the Getting Started guide for additional information.\n",
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003291 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07003292#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003293 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
3294 " extension.\n\n"
3295 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3296 "Please look at the Getting Started guide for additional information.\n",
Damien Leone600c3052017-01-31 10:26:07 -07003297 "vkCreateInstance Failure");
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003298#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003299 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
3300 " extension.\n\n"
3301 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3302 "Please look at the Getting Started guide for additional information.\n",
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003303 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07003304#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003305 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
3306 " extension.\n\n"
3307 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3308 "Please look at the Getting Started guide for additional information.\n",
Tony Barbour2593b182016-04-19 10:57:58 -06003309 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003310#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3311 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
3312 " extension.\n\n"
3313 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3314 "Please look at the Getting Started guide for additional information.\n",
3315 "vkCreateInstance Failure");
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003316#endif
Tony Barbour153cb062016-12-07 13:43:36 -07003317 }
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06003318 const VkApplicationInfo app = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06003319 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003320 .pNext = NULL,
Chia-I Wua8fe78a2015-10-27 18:04:07 +08003321 .pApplicationName = APP_SHORT_NAME,
3322 .applicationVersion = 0,
Ian Elliott44e33f72015-04-28 10:52:52 -06003323 .pEngineName = APP_SHORT_NAME,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003324 .engineVersion = 0,
Jon Ashburn7f4bc2c2016-03-22 13:57:46 -06003325 .apiVersion = VK_API_VERSION_1_0,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003326 };
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003327 VkInstanceCreateInfo inst_info = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06003328 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
Jon Ashburnab46b362015-04-04 14:52:07 -06003329 .pNext = NULL,
Charles Giessen5f3ce242022-04-11 14:39:06 -06003330 .flags = (portabilityEnumerationActive ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0),
Chia-I Wua8fe78a2015-10-27 18:04:07 +08003331 .pApplicationInfo = &app,
Karl Schultz7c50ad62016-04-01 12:07:03 -06003332 .enabledLayerCount = demo->enabled_layer_count,
3333 .ppEnabledLayerNames = (const char *const *)instance_validation_layers,
3334 .enabledExtensionCount = demo->enabled_extension_count,
3335 .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
Jon Ashburnab46b362015-04-04 14:52:07 -06003336 };
Karl Schultzcd9887d2016-03-25 14:25:16 -06003337
3338 /*
3339 * This is info for a temp callback to use during CreateInstance.
3340 * After the instance is created, we use the instance-based
3341 * function to register the final callback.
3342 */
Mark Young66510e52017-11-10 10:05:14 -07003343 VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info;
Ian Elliott5959bbd2016-03-25 09:07:19 -06003344 if (demo->validate) {
Mark Young66510e52017-11-10 10:05:14 -07003345 // VK_EXT_debug_utils style
3346 dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
3347 dbg_messenger_create_info.pNext = NULL;
3348 dbg_messenger_create_info.flags = 0;
3349 dbg_messenger_create_info.messageSeverity =
3350 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
3351 dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
3352 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
3353 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
3354 dbg_messenger_create_info.pfnUserCallback = debug_messenger_callback;
3355 dbg_messenger_create_info.pUserData = demo;
3356 inst_info.pNext = &dbg_messenger_create_info;
Ian Elliott5959bbd2016-03-25 09:07:19 -06003357 }
Ian Elliott097d9f32015-04-28 11:35:02 -06003358
Chia-I Wu63636062015-10-26 21:10:41 +08003359 err = vkCreateInstance(&inst_info, NULL, &demo->inst);
Ian Elliott07264132015-04-28 11:35:02 -06003360 if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003361 ERR_EXIT(
3362 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
3363 "Please look at the Getting Started guide for additional information.\n",
3364 "vkCreateInstance Failure");
Courtney Goeltzenleuchter1e47e4b2015-09-14 18:01:17 -06003365 } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003366 ERR_EXIT(
3367 "Cannot find a specified extension library.\n"
3368 "Make sure your layers path is set appropriately.\n",
3369 "vkCreateInstance Failure");
Ian Elliott07264132015-04-28 11:35:02 -06003370 } else if (err) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003371 ERR_EXIT(
3372 "vkCreateInstance failed.\n\n"
3373 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3374 "Please look at the Getting Started guide for additional information.\n",
3375 "vkCreateInstance Failure");
Ian Elliott3979e282015-04-03 15:24:55 -06003376 }
Jon Ashburnab46b362015-04-04 14:52:07 -06003377
Witold Baryluka3b988f2021-01-07 19:03:02 +00003378 /* Make initial call to query gpu_count, then second call for gpu info */
3379 uint32_t gpu_count = 0;
Tobin Ehlis8a724d82015-09-07 15:16:39 -06003380 err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL);
Petr Kraus2f1dbdb2018-04-14 14:45:17 +02003381 assert(!err);
Dustin Graves7c287352016-01-27 13:48:06 -07003382
Witold Baryluka3b988f2021-01-07 19:03:02 +00003383 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003384 ERR_EXIT(
3385 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
3386 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3387 "Please look at the Getting Started guide for additional information.\n",
3388 "vkEnumeratePhysicalDevices Failure");
Dustin Graves7c287352016-01-27 13:48:06 -07003389 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003390
Witold Baryluka3b988f2021-01-07 19:03:02 +00003391 VkPhysicalDevice *physical_devices = malloc(sizeof(VkPhysicalDevice) * gpu_count);
3392 err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, physical_devices);
3393 assert(!err);
3394 if (demo->gpu_number >= 0 && !((uint32_t)demo->gpu_number < gpu_count)) {
3395 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", demo->gpu_number, gpu_count);
3396 ERR_EXIT("Specified GPU number is not present", "User Error");
3397 }
3398
Tony-LunarG27c21242021-03-11 16:28:19 -07003399#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
3400 demo->gpu_number = find_display_gpu(demo->gpu_number, gpu_count, physical_devices);
3401 if (demo->gpu_number < 0) {
3402 printf("Cannot find any display!\n");
3403 fflush(stdout);
3404 exit(1);
3405 }
3406#else
Witold Baryluka3b988f2021-01-07 19:03:02 +00003407 /* Try to auto select most suitable device */
3408 if (demo->gpu_number == -1) {
3409 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
3410 memset(count_device_type, 0, sizeof(count_device_type));
3411
3412 VkPhysicalDeviceProperties physicalDeviceProperties;
3413 for (uint32_t i = 0; i < gpu_count; i++) {
3414 vkGetPhysicalDeviceProperties(physical_devices[i], &physicalDeviceProperties);
3415 assert(physicalDeviceProperties.deviceType <= VK_PHYSICAL_DEVICE_TYPE_CPU);
3416 count_device_type[physicalDeviceProperties.deviceType]++;
3417 }
3418
3419 VkPhysicalDeviceType search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
3420 if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU]) {
3421 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
3422 } else if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU]) {
3423 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
3424 } else if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU]) {
3425 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU;
3426 } else if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU]) {
3427 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_CPU;
3428 } else if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_OTHER]) {
3429 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_OTHER;
3430 }
3431
3432 for (uint32_t i = 0; i < gpu_count; i++) {
3433 vkGetPhysicalDeviceProperties(physical_devices[i], &physicalDeviceProperties);
3434 if (physicalDeviceProperties.deviceType == search_for_device_type) {
3435 demo->gpu_number = i;
3436 break;
3437 }
3438 }
3439 }
Tony-LunarG27c21242021-03-11 16:28:19 -07003440#endif
Witold Baryluka3b988f2021-01-07 19:03:02 +00003441 assert(demo->gpu_number >= 0);
3442 demo->gpu = physical_devices[demo->gpu_number];
3443 {
3444 VkPhysicalDeviceProperties physicalDeviceProperties;
3445 vkGetPhysicalDeviceProperties(demo->gpu, &physicalDeviceProperties);
Jeremy Hayes5f9e5f12022-02-09 15:04:42 -07003446 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", demo->gpu_number, physicalDeviceProperties.deviceName,
3447 to_string(physicalDeviceProperties.deviceType));
Witold Baryluka3b988f2021-01-07 19:03:02 +00003448 }
3449 free(physical_devices);
3450
Dustin Graves7c287352016-01-27 13:48:06 -07003451 /* Look for device extensions */
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003452 uint32_t device_extension_count = 0;
Dustin Graves7c287352016-01-27 13:48:06 -07003453 VkBool32 swapchainExtFound = 0;
3454 demo->enabled_extension_count = 0;
Karl Schultz7c50ad62016-04-01 12:07:03 -06003455 memset(demo->extension_names, 0, sizeof(demo->extension_names));
Dustin Graves7c287352016-01-27 13:48:06 -07003456
Dave Houlton5fa47912018-02-16 11:02:26 -07003457 err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, NULL);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003458 assert(!err);
3459
Dustin Graves7c287352016-01-27 13:48:06 -07003460 if (device_extension_count > 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003461 VkExtensionProperties *device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count);
3462 err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, device_extensions);
Dustin Graves7c287352016-01-27 13:48:06 -07003463 assert(!err);
Ian Elliottaaae5352015-07-06 14:27:58 -06003464
Dustin Graves7c287352016-01-27 13:48:06 -07003465 for (uint32_t i = 0; i < device_extension_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003466 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
Dustin Graves7c287352016-01-27 13:48:06 -07003467 swapchainExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003468 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Dustin Graves7c287352016-01-27 13:48:06 -07003469 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05003470 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
3471 demo->extension_names[demo->enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05003472 }
Dustin Graves7c287352016-01-27 13:48:06 -07003473 assert(demo->enabled_extension_count < 64);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003474 }
Dustin Graves7c287352016-01-27 13:48:06 -07003475
Ian Elliott53622a72017-03-28 11:06:33 -06003476 if (demo->VK_KHR_incremental_present_enabled) {
3477 // Even though the user "enabled" the extension via the command
3478 // line, we must make sure that it's enumerated for use with the
3479 // device. Therefore, disable it here, and re-enable it again if
3480 // enumerated.
3481 demo->VK_KHR_incremental_present_enabled = false;
3482 for (uint32_t i = 0; i < device_extension_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003483 if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, device_extensions[i].extensionName)) {
3484 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME;
Ian Elliott53622a72017-03-28 11:06:33 -06003485 demo->VK_KHR_incremental_present_enabled = true;
3486 DbgMsg("VK_KHR_incremental_present extension enabled\n");
3487 }
3488 assert(demo->enabled_extension_count < 64);
3489 }
3490 if (!demo->VK_KHR_incremental_present_enabled) {
3491 DbgMsg("VK_KHR_incremental_present extension NOT AVAILABLE\n");
3492 }
3493 }
3494
Ian Elliottd940ca22017-03-22 08:31:27 -06003495 if (demo->VK_GOOGLE_display_timing_enabled) {
3496 // Even though the user "enabled" the extension via the command
3497 // line, we must make sure that it's enumerated for use with the
3498 // device. Therefore, disable it here, and re-enable it again if
3499 // enumerated.
3500 demo->VK_GOOGLE_display_timing_enabled = false;
3501 for (uint32_t i = 0; i < device_extension_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003502 if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, device_extensions[i].extensionName)) {
3503 demo->extension_names[demo->enabled_extension_count++] = VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME;
Ian Elliottd940ca22017-03-22 08:31:27 -06003504 demo->VK_GOOGLE_display_timing_enabled = true;
Ian Elliott0c7b3c92017-03-27 14:38:52 -06003505 DbgMsg("VK_GOOGLE_display_timing extension enabled\n");
Ian Elliottd940ca22017-03-22 08:31:27 -06003506 }
3507 assert(demo->enabled_extension_count < 64);
3508 }
3509 if (!demo->VK_GOOGLE_display_timing_enabled) {
Ian Elliott0c7b3c92017-03-27 14:38:52 -06003510 DbgMsg("VK_GOOGLE_display_timing extension NOT AVAILABLE\n");
Ian Elliottd940ca22017-03-22 08:31:27 -06003511 }
3512 }
3513
Dustin Graves7c287352016-01-27 13:48:06 -07003514 free(device_extensions);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003515 }
Dustin Graves7c287352016-01-27 13:48:06 -07003516
Tony Barbourcc69f452015-10-08 13:59:42 -06003517 if (!swapchainExtFound) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003518 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
3519 " extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\n"
3520 "Please look at the Getting Started guide for additional information.\n",
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003521 "vkCreateInstance Failure");
3522 }
3523
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003524 if (demo->validate) {
Mark Young66510e52017-11-10 10:05:14 -07003525 // Setup VK_EXT_debug_utils function pointers always (we use them for
3526 // debug labels and names).
3527 demo->CreateDebugUtilsMessengerEXT =
3528 (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkCreateDebugUtilsMessengerEXT");
3529 demo->DestroyDebugUtilsMessengerEXT =
3530 (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkDestroyDebugUtilsMessengerEXT");
3531 demo->SubmitDebugUtilsMessageEXT =
3532 (PFN_vkSubmitDebugUtilsMessageEXT)vkGetInstanceProcAddr(demo->inst, "vkSubmitDebugUtilsMessageEXT");
3533 demo->CmdBeginDebugUtilsLabelEXT =
3534 (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdBeginDebugUtilsLabelEXT");
3535 demo->CmdEndDebugUtilsLabelEXT =
3536 (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdEndDebugUtilsLabelEXT");
3537 demo->CmdInsertDebugUtilsLabelEXT =
3538 (PFN_vkCmdInsertDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdInsertDebugUtilsLabelEXT");
3539 demo->SetDebugUtilsObjectNameEXT =
3540 (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(demo->inst, "vkSetDebugUtilsObjectNameEXT");
3541 if (NULL == demo->CreateDebugUtilsMessengerEXT || NULL == demo->DestroyDebugUtilsMessengerEXT ||
3542 NULL == demo->SubmitDebugUtilsMessageEXT || NULL == demo->CmdBeginDebugUtilsLabelEXT ||
3543 NULL == demo->CmdEndDebugUtilsLabelEXT || NULL == demo->CmdInsertDebugUtilsLabelEXT ||
3544 NULL == demo->SetDebugUtilsObjectNameEXT) {
3545 ERR_EXIT("GetProcAddr: Failed to init VK_EXT_debug_utils\n", "GetProcAddr: Failure");
Courtney Goeltzenleuchteraf1951c2015-12-01 14:11:38 -07003546 }
Jon Ashburn9549c8e2015-12-15 08:47:46 -07003547
Mark Young66510e52017-11-10 10:05:14 -07003548 err = demo->CreateDebugUtilsMessengerEXT(demo->inst, &dbg_messenger_create_info, NULL, &demo->dbg_messenger);
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -06003549 switch (err) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003550 case VK_SUCCESS:
3551 break;
3552 case VK_ERROR_OUT_OF_HOST_MEMORY:
Mark Young66510e52017-11-10 10:05:14 -07003553 ERR_EXIT("CreateDebugUtilsMessengerEXT: out of host memory\n", "CreateDebugUtilsMessengerEXT Failure");
Dave Houlton5fa47912018-02-16 11:02:26 -07003554 break;
3555 default:
Mark Young66510e52017-11-10 10:05:14 -07003556 ERR_EXIT("CreateDebugUtilsMessengerEXT: unknown failure\n", "CreateDebugUtilsMessengerEXT Failure");
Dave Houlton5fa47912018-02-16 11:02:26 -07003557 break;
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -06003558 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003559 }
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06003560 vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props);
Tobin Ehlis9626ba62015-09-22 13:52:37 -06003561
3562 /* Call with NULL data to get count */
Dave Houlton5fa47912018-02-16 11:02:26 -07003563 vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, NULL);
Tony Barbourab2a0362016-09-06 11:40:12 -06003564 assert(demo->queue_family_count >= 1);
Tobin Ehlis9626ba62015-09-22 13:52:37 -06003565
Dave Houlton5fa47912018-02-16 11:02:26 -07003566 demo->queue_props = (VkQueueFamilyProperties *)malloc(demo->queue_family_count * sizeof(VkQueueFamilyProperties));
3567 vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, demo->queue_props);
Tony Barbourab2a0362016-09-06 11:40:12 -06003568
Tobin Ehlisbf3020e2015-09-24 15:18:22 -06003569 // Query fine-grained feature support for this device.
Karl Schultze4dc75c2016-02-02 15:37:51 -07003570 // If app has specific feature requirements it should check supported
3571 // features based on this query
Tobin Ehlis8d03b7c2015-09-29 11:22:37 -06003572 VkPhysicalDeviceFeatures physDevFeatures;
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06003573 vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures);
Tobin Ehlisbf3020e2015-09-24 15:18:22 -06003574
Tony Barbourda2bad52016-01-22 14:36:40 -07003575 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceSupportKHR);
3576 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceCapabilitiesKHR);
3577 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceFormatsKHR);
3578 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfacePresentModesKHR);
3579 GET_INSTANCE_PROC_ADDR(demo->inst, GetSwapchainImagesKHR);
3580}
3581
Karl Schultze4dc75c2016-02-02 15:37:51 -07003582static void demo_create_device(struct demo *demo) {
Tony Barbourda2bad52016-01-22 14:36:40 -07003583 VkResult U_ASSERT_ONLY err;
Karl Schultze4dc75c2016-02-02 15:37:51 -07003584 float queue_priorities[1] = {0.0};
Tony Barbour22e06272016-09-07 16:07:56 -06003585 VkDeviceQueueCreateInfo queues[2];
3586 queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3587 queues[0].pNext = NULL;
3588 queues[0].queueFamilyIndex = demo->graphics_queue_family_index;
3589 queues[0].queueCount = 1;
3590 queues[0].pQueuePriorities = queue_priorities;
3591 queues[0].flags = 0;
Tobin Ehlis9626ba62015-09-22 13:52:37 -06003592
3593 VkDeviceCreateInfo device = {
3594 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
3595 .pNext = NULL,
Chia-I Wu8b497442015-11-06 06:42:02 +08003596 .queueCreateInfoCount = 1,
Tony Barbour22e06272016-09-07 16:07:56 -06003597 .pQueueCreateInfos = queues,
Karl Schultz5b423ea2016-06-20 19:08:43 -06003598 .enabledLayerCount = 0,
3599 .ppEnabledLayerNames = NULL,
Tony Barbourda2bad52016-01-22 14:36:40 -07003600 .enabledExtensionCount = demo->enabled_extension_count,
Karl Schultze4dc75c2016-02-02 15:37:51 -07003601 .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
Dave Houlton5fa47912018-02-16 11:02:26 -07003602 .pEnabledFeatures = NULL, // If specific features are required, pass them in here
Tobin Ehlis9626ba62015-09-22 13:52:37 -06003603 };
Tony Barbour22e06272016-09-07 16:07:56 -06003604 if (demo->separate_present_queue) {
3605 queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3606 queues[1].pNext = NULL;
3607 queues[1].queueFamilyIndex = demo->present_queue_family_index;
3608 queues[1].queueCount = 1;
3609 queues[1].pQueuePriorities = queue_priorities;
3610 queues[1].flags = 0;
3611 device.queueCreateInfoCount = 2;
3612 }
Chia-I Wu63636062015-10-26 21:10:41 +08003613 err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003614 assert(!err);
Courtney Goeltzenleuchter3a35c822015-07-15 17:45:38 -06003615}
3616
Tony-LunarG6cebf142019-09-11 14:32:23 -06003617static void demo_create_surface(struct demo *demo) {
Courtney Goeltzenleuchterd3cdaaf2015-12-17 09:53:29 -07003618 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchtered667a52015-03-05 18:09:39 -07003619
Karl Schultze4dc75c2016-02-02 15:37:51 -07003620// Create a WSI surface for the window:
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003621#if defined(VK_USE_PLATFORM_WIN32_KHR)
Ian Elliotta7a731c2015-12-11 15:52:12 -07003622 VkWin32SurfaceCreateInfoKHR createInfo;
3623 createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
3624 createInfo.pNext = NULL;
3625 createInfo.flags = 0;
Jon Ashburnb90f50d2015-12-24 17:08:01 -07003626 createInfo.hinstance = demo->connection;
3627 createInfo.hwnd = demo->window;
Ian Elliotta7a731c2015-12-11 15:52:12 -07003628
Dave Houlton5fa47912018-02-16 11:02:26 -07003629 err = vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Tony Barbour153cb062016-12-07 13:43:36 -07003630#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003631 VkWaylandSurfaceCreateInfoKHR createInfo;
3632 createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
3633 createInfo.pNext = NULL;
3634 createInfo.flags = 0;
3635 createInfo.display = demo->display;
3636 createInfo.surface = demo->window;
3637
Dave Houlton5fa47912018-02-16 11:02:26 -07003638 err = vkCreateWaylandSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003639#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3640 VkAndroidSurfaceCreateInfoKHR createInfo;
3641 createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
3642 createInfo.pNext = NULL;
3643 createInfo.flags = 0;
Mike Schuchardt837d5162018-03-08 12:57:02 -07003644 createInfo.window = (struct ANativeWindow *)(demo->window);
Ian Elliottb08e0d92015-11-20 11:55:46 -07003645
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003646 err = vkCreateAndroidSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Tony Barbour153cb062016-12-07 13:43:36 -07003647#elif defined(VK_USE_PLATFORM_XLIB_KHR)
3648 VkXlibSurfaceCreateInfoKHR createInfo;
3649 createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
3650 createInfo.pNext = NULL;
3651 createInfo.flags = 0;
3652 createInfo.dpy = demo->display;
3653 createInfo.window = demo->xlib_window;
Ian Elliotta7a731c2015-12-11 15:52:12 -07003654
Dave Houlton5fa47912018-02-16 11:02:26 -07003655 err = vkCreateXlibSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Tony Barbour153cb062016-12-07 13:43:36 -07003656#elif defined(VK_USE_PLATFORM_XCB_KHR)
3657 VkXcbSurfaceCreateInfoKHR createInfo;
3658 createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
3659 createInfo.pNext = NULL;
3660 createInfo.flags = 0;
3661 createInfo.connection = demo->connection;
3662 createInfo.window = demo->xcb_window;
Tony Barbour2593b182016-04-19 10:57:58 -06003663
Tony Barbour153cb062016-12-07 13:43:36 -07003664 err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003665#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3666 VkDirectFBSurfaceCreateInfoEXT createInfo;
3667 createInfo.sType = VK_STRUCTURE_TYPE_DIRECTFB_SURFACE_CREATE_INFO_EXT;
3668 createInfo.pNext = NULL;
3669 createInfo.flags = 0;
3670 createInfo.dfb = demo->dfb;
3671 createInfo.surface = demo->window;
3672
3673 err = vkCreateDirectFBSurfaceEXT(demo->inst, &createInfo, NULL, &demo->surface);
Damien Leone600c3052017-01-31 10:26:07 -07003674#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3675 err = demo_create_display_surface(demo);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003676#elif defined(VK_USE_PLATFORM_METAL_EXT)
3677 VkMetalSurfaceCreateInfoEXT surface;
3678 surface.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
Bill Hollingsf4352142017-02-14 22:58:56 -05003679 surface.pNext = NULL;
3680 surface.flags = 0;
Bill Hollings0a0625a2019-07-15 17:39:18 -04003681 surface.pLayer = demo->caMetalLayer;
Bill Hollingsf4352142017-02-14 22:58:56 -05003682
Bill Hollings0a0625a2019-07-15 17:39:18 -04003683 err = vkCreateMetalSurfaceEXT(demo->inst, &surface, NULL, &demo->surface);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003684#endif
Tony Barbour2593b182016-04-19 10:57:58 -06003685 assert(!err);
Tony-LunarG6cebf142019-09-11 14:32:23 -06003686}
3687
Joshua Ashton1fbefe02020-04-02 06:45:48 +01003688static VkSurfaceFormatKHR pick_surface_format(const VkSurfaceFormatKHR *surfaceFormats, uint32_t count) {
3689 // Prefer non-SRGB formats...
3690 for (uint32_t i = 0; i < count; i++) {
3691 const VkFormat format = surfaceFormats[i].format;
3692
3693 if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_B8G8R8A8_UNORM ||
3694 format == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || format == VK_FORMAT_A2R10G10B10_UNORM_PACK32 ||
3695 format == VK_FORMAT_R16G16B16A16_SFLOAT) {
3696 return surfaceFormats[i];
3697 }
3698 }
3699
3700 printf("Can't find our preferred formats... Falling back to first exposed format. Rendering may be incorrect.\n");
3701
3702 assert(count >= 1);
3703 return surfaceFormats[0];
3704}
3705
Tony-LunarG6cebf142019-09-11 14:32:23 -06003706static void demo_init_vk_swapchain(struct demo *demo) {
3707 VkResult U_ASSERT_ONLY err;
3708
3709 demo_create_surface(demo);
Ian Elliottaaae5352015-07-06 14:27:58 -06003710
Tony Barbourcc69f452015-10-08 13:59:42 -06003711 // Iterate over each queue to learn whether it supports presenting:
Dave Houlton5fa47912018-02-16 11:02:26 -07003712 VkBool32 *supportsPresent = (VkBool32 *)malloc(demo->queue_family_count * sizeof(VkBool32));
Karl Schultza2615462017-01-20 13:19:20 -07003713 for (uint32_t i = 0; i < demo->queue_family_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003714 demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]);
Courtney Goeltzenleuchtered667a52015-03-05 18:09:39 -07003715 }
Ian Elliottaaae5352015-07-06 14:27:58 -06003716
3717 // Search for a graphics and a present queue in the array of queue
3718 // families, try to find one that supports both
Tony Barbourab2a0362016-09-06 11:40:12 -06003719 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
3720 uint32_t presentQueueFamilyIndex = UINT32_MAX;
Karl Schultza2615462017-01-20 13:19:20 -07003721 for (uint32_t i = 0; i < demo->queue_family_count; i++) {
Tony Barbourab2a0362016-09-06 11:40:12 -06003722 if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
3723 if (graphicsQueueFamilyIndex == UINT32_MAX) {
3724 graphicsQueueFamilyIndex = i;
3725 }
Karl Schultze4dc75c2016-02-02 15:37:51 -07003726
Tony Barbourab2a0362016-09-06 11:40:12 -06003727 if (supportsPresent[i] == VK_TRUE) {
3728 graphicsQueueFamilyIndex = i;
3729 presentQueueFamilyIndex = i;
3730 break;
3731 }
3732 }
3733 }
3734
3735 if (presentQueueFamilyIndex == UINT32_MAX) {
3736 // If didn't find a queue that supports both graphics and present, then
3737 // find a separate present queue.
Karl Schultza2615462017-01-20 13:19:20 -07003738 for (uint32_t i = 0; i < demo->queue_family_count; ++i) {
Tony Barbourab2a0362016-09-06 11:40:12 -06003739 if (supportsPresent[i] == VK_TRUE) {
3740 presentQueueFamilyIndex = i;
3741 break;
3742 }
Ian Elliottaaae5352015-07-06 14:27:58 -06003743 }
3744 }
Ian Elliottaaae5352015-07-06 14:27:58 -06003745
3746 // Generate error if could not find both a graphics and a present queue
Dave Houlton5fa47912018-02-16 11:02:26 -07003747 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
3748 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
Ian Elliottaaae5352015-07-06 14:27:58 -06003749 }
3750
Tony Barbourab2a0362016-09-06 11:40:12 -06003751 demo->graphics_queue_family_index = graphicsQueueFamilyIndex;
3752 demo->present_queue_family_index = presentQueueFamilyIndex;
Dave Houlton5fa47912018-02-16 11:02:26 -07003753 demo->separate_present_queue = (demo->graphics_queue_family_index != demo->present_queue_family_index);
Tony Barbourab2a0362016-09-06 11:40:12 -06003754 free(supportsPresent);
Courtney Goeltzenleuchtered667a52015-03-05 18:09:39 -07003755
Tony Barbourda2bad52016-01-22 14:36:40 -07003756 demo_create_device(demo);
3757
3758 GET_DEVICE_PROC_ADDR(demo->device, CreateSwapchainKHR);
3759 GET_DEVICE_PROC_ADDR(demo->device, DestroySwapchainKHR);
3760 GET_DEVICE_PROC_ADDR(demo->device, GetSwapchainImagesKHR);
3761 GET_DEVICE_PROC_ADDR(demo->device, AcquireNextImageKHR);
3762 GET_DEVICE_PROC_ADDR(demo->device, QueuePresentKHR);
Ian Elliottd940ca22017-03-22 08:31:27 -06003763 if (demo->VK_GOOGLE_display_timing_enabled) {
3764 GET_DEVICE_PROC_ADDR(demo->device, GetRefreshCycleDurationGOOGLE);
3765 GET_DEVICE_PROC_ADDR(demo->device, GetPastPresentationTimingGOOGLE);
3766 }
Tony Barbourda2bad52016-01-22 14:36:40 -07003767
Dave Houlton5fa47912018-02-16 11:02:26 -07003768 vkGetDeviceQueue(demo->device, demo->graphics_queue_family_index, 0, &demo->graphics_queue);
Tony Barboura2a67812016-07-18 13:21:06 -06003769
Tony Barbour22e06272016-09-07 16:07:56 -06003770 if (!demo->separate_present_queue) {
Tony Barboura2a67812016-07-18 13:21:06 -06003771 demo->present_queue = demo->graphics_queue;
3772 } else {
Dave Houlton5fa47912018-02-16 11:02:26 -07003773 vkGetDeviceQueue(demo->device, demo->present_queue_family_index, 0, &demo->present_queue);
Tony Barboura2a67812016-07-18 13:21:06 -06003774 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003775
Ian Elliottaaae5352015-07-06 14:27:58 -06003776 // Get the list of VkFormat's that are supported:
Ian Elliott8528eff2015-08-07 15:56:59 -06003777 uint32_t formatCount;
Dave Houlton5fa47912018-02-16 11:02:26 -07003778 err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL);
Ian Elliottaaae5352015-07-06 14:27:58 -06003779 assert(!err);
Dave Houlton5fa47912018-02-16 11:02:26 -07003780 VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
3781 err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats);
Ian Elliottaaae5352015-07-06 14:27:58 -06003782 assert(!err);
Joshua Ashton1fbefe02020-04-02 06:45:48 +01003783 VkSurfaceFormatKHR surfaceFormat = pick_surface_format(surfFormats, formatCount);
3784 demo->format = surfaceFormat.format;
3785 demo->color_space = surfaceFormat.colorSpace;
Jason Chen5d4fee92019-04-04 12:45:29 +08003786 free(surfFormats);
Ian Elliotte4602cd2015-04-21 16:41:02 -06003787
David Pinedo2bb7c932015-06-18 17:03:14 -06003788 demo->quit = false;
3789 demo->curFrame = 0;
Mark Lobodzinskieadf9982015-07-02 16:49:40 -06003790
Tony Barbource7524e2016-07-28 12:01:45 -06003791 // Create semaphores to synchronize acquiring presentable buffers before
3792 // rendering and waiting for drawing to be complete before presenting
3793 VkSemaphoreCreateInfo semaphoreCreateInfo = {
3794 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
3795 .pNext = NULL,
3796 .flags = 0,
3797 };
Tony Barbource7524e2016-07-28 12:01:45 -06003798
Tony Barbour66a56c32016-09-21 13:10:56 -06003799 // Create fences that we can use to throttle if we get too far
3800 // ahead of the image presents
3801 VkFenceCreateInfo fence_ci = {
Dave Houlton5fa47912018-02-16 11:02:26 -07003802 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = VK_FENCE_CREATE_SIGNALED_BIT};
Tony Barbour66a56c32016-09-21 13:10:56 -06003803 for (uint32_t i = 0; i < FRAME_LAG; i++) {
Tony Barboura72d9492017-01-11 13:35:09 -07003804 err = vkCreateFence(demo->device, &fence_ci, NULL, &demo->fences[i]);
3805 assert(!err);
3806
Dave Houlton5fa47912018-02-16 11:02:26 -07003807 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_acquired_semaphores[i]);
Tony Barbour22e06272016-09-07 16:07:56 -06003808 assert(!err);
Tony Barbour66a56c32016-09-21 13:10:56 -06003809
Dave Houlton5fa47912018-02-16 11:02:26 -07003810 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->draw_complete_semaphores[i]);
Tony Barbour66a56c32016-09-21 13:10:56 -06003811 assert(!err);
3812
3813 if (demo->separate_present_queue) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003814 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_ownership_semaphores[i]);
Tony Barbour66a56c32016-09-21 13:10:56 -06003815 assert(!err);
3816 }
Tony Barbour22e06272016-09-07 16:07:56 -06003817 }
Tony Barbour66a56c32016-09-21 13:10:56 -06003818 demo->frame_index = 0;
Tony Barbour22e06272016-09-07 16:07:56 -06003819
Mark Lobodzinskieadf9982015-07-02 16:49:40 -06003820 // Get Memory information and properties
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06003821 vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003822}
3823
Tony Barbour153cb062016-12-07 13:43:36 -07003824#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdek15eb0702017-06-07 09:40:36 -06003825static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
3826 wl_fixed_t sy) {}
3827
3828static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
3829
3830static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
3831
3832static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
3833 uint32_t state) {
3834 struct demo *demo = data;
3835 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Manuel Stoecklac939332019-06-26 20:55:53 -04003836 xdg_toplevel_move(demo->xdg_toplevel, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -06003837 }
3838}
3839
3840static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
3841
3842static const struct wl_pointer_listener pointer_listener = {
3843 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
3844};
3845
3846static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
3847
3848static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
3849 struct wl_array *keys) {}
3850
3851static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
3852
3853static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
3854 uint32_t state) {
3855 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
3856 struct demo *demo = data;
3857 switch (key) {
3858 case KEY_ESC: // Escape
3859 demo->quit = true;
3860 break;
3861 case KEY_LEFT: // left arrow key
3862 demo->spin_angle -= demo->spin_increment;
3863 break;
3864 case KEY_RIGHT: // right arrow key
3865 demo->spin_angle += demo->spin_increment;
3866 break;
3867 case KEY_SPACE: // space bar
3868 demo->pause = !demo->pause;
3869 break;
3870 }
3871}
3872
3873static void keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
3874 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
3875
3876static const struct wl_keyboard_listener keyboard_listener = {
3877 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
3878};
3879
3880static void seat_handle_capabilities(void *data, struct wl_seat *seat, enum wl_seat_capability caps) {
3881 // Subscribe to pointer events
3882 struct demo *demo = data;
3883 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
3884 demo->pointer = wl_seat_get_pointer(seat);
3885 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
3886 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
3887 wl_pointer_destroy(demo->pointer);
3888 demo->pointer = NULL;
3889 }
3890 // Subscribe to keyboard events
3891 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
3892 demo->keyboard = wl_seat_get_keyboard(seat);
3893 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
shironeko689140c2022-05-19 10:21:07 -04003894 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && demo->keyboard) {
Joey Bzdek15eb0702017-06-07 09:40:36 -06003895 wl_keyboard_destroy(demo->keyboard);
3896 demo->keyboard = NULL;
3897 }
3898}
3899
3900static const struct wl_seat_listener seat_listener = {
3901 seat_handle_capabilities,
3902};
3903
Manuel Stoecklac939332019-06-26 20:55:53 -04003904static void wm_base_ping(void *data UNUSED, struct xdg_wm_base *xdg_wm_base, uint32_t serial) {
3905 xdg_wm_base_pong(xdg_wm_base, serial);
3906}
3907
3908static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
3909
3910static void registry_handle_global(void *data, struct wl_registry *registry, uint32_t id, const char *interface,
3911 uint32_t version UNUSED) {
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003912 struct demo *demo = data;
Joey Bzdek15eb0702017-06-07 09:40:36 -06003913 // pickup wayland objects when they appear
Manuel Stoecklac939332019-06-26 20:55:53 -04003914 if (strcmp(interface, wl_compositor_interface.name) == 0) {
Georges Basile Stavracas Neto7da3ea72019-10-05 11:53:39 -03003915 uint32_t minVersion = version < 4 ? version : 4;
3916 demo->compositor = wl_registry_bind(registry, id, &wl_compositor_interface, minVersion);
3917 if (demo->VK_KHR_incremental_present_enabled && minVersion < 4) {
3918 fprintf(stderr, "Wayland compositor doesn't support VK_KHR_incremental_present, disabling.\n");
3919 demo->VK_KHR_incremental_present_enabled = false;
3920 }
Manuel Stoecklac939332019-06-26 20:55:53 -04003921 } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
3922 demo->xdg_wm_base = wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
3923 xdg_wm_base_add_listener(demo->xdg_wm_base, &wm_base_listener, NULL);
3924 } else if (strcmp(interface, wl_seat_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -06003925 demo->seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
3926 wl_seat_add_listener(demo->seat, &seat_listener, demo);
Manuel Stoecklac939332019-06-26 20:55:53 -04003927 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
3928 demo->xdg_decoration_mgr = wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003929 }
3930}
3931
Dave Houlton5fa47912018-02-16 11:02:26 -07003932static void registry_handle_global_remove(void *data UNUSED, struct wl_registry *registry UNUSED, uint32_t name UNUSED) {}
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003933
Dave Houlton5fa47912018-02-16 11:02:26 -07003934static const struct wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003935#endif
3936
Karl Schultze4dc75c2016-02-02 15:37:51 -07003937static void demo_init_connection(struct demo *demo) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003938#if defined(VK_USE_PLATFORM_XCB_KHR)
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003939 const xcb_setup_t *setup;
3940 xcb_screen_iterator_t iter;
3941 int scr;
3942
Mike Weiblen5d2ad542018-02-13 13:56:13 -07003943 const char *display_envar = getenv("DISPLAY");
3944 if (display_envar == NULL || display_envar[0] == '\0') {
3945 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
3946 fflush(stdout);
3947 exit(1);
3948 }
3949
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003950 demo->connection = xcb_connect(NULL, &scr);
Lenny Komow022bc2a2016-08-11 10:57:38 -06003951 if (xcb_connection_has_error(demo->connection) > 0) {
C Stout05c61712021-08-20 13:19:01 -07003952 printf("Cannot connect to XCB.\nExiting ...\n");
Ian Elliott3979e282015-04-03 15:24:55 -06003953 fflush(stdout);
3954 exit(1);
3955 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003956
3957 setup = xcb_get_setup(demo->connection);
3958 iter = xcb_setup_roots_iterator(setup);
Dave Houlton5fa47912018-02-16 11:02:26 -07003959 while (scr-- > 0) xcb_screen_next(&iter);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003960
3961 demo->screen = iter.data;
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003962#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3963 demo->display = wl_display_connect(NULL);
3964
3965 if (demo->display == NULL) {
C Stout05c61712021-08-20 13:19:01 -07003966 printf("Cannot connect to wayland.\nExiting ...\n");
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003967 fflush(stdout);
3968 exit(1);
3969 }
3970
3971 demo->registry = wl_display_get_registry(demo->display);
3972 wl_registry_add_listener(demo->registry, &registry_listener, demo);
3973 wl_display_dispatch(demo->display);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003974#endif
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003975}
3976
Karl Schultze4dc75c2016-02-02 15:37:51 -07003977static void demo_init(struct demo *demo, int argc, char **argv) {
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -06003978 vec3 eye = {0.0f, 3.0f, 5.0f};
3979 vec3 origin = {0, 0, 0};
Chia-I Wuae3b55d2015-04-22 14:56:17 +08003980 vec3 up = {0.0f, 1.0f, 0.0};
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -06003981
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003982 memset(demo, 0, sizeof(*demo));
Tony Barbour291d57b2016-10-21 14:47:07 -06003983 demo->presentMode = VK_PRESENT_MODE_FIFO_KHR;
Tony Barbour1a86d032015-09-21 15:17:33 -06003984 demo->frameCount = INT32_MAX;
Witold Baryluka3b988f2021-01-07 19:03:02 +00003985 /* Autodetect suitable / best GPU by default */
3986 demo->gpu_number = -1;
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +01003987 demo->width = 500;
3988 demo->height = 500;
Jeremy Kniager979b5312019-11-22 14:55:57 -07003989
Piers Daniell735ee532015-02-23 16:23:13 -07003990 for (int i = 1; i < argc; i++) {
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003991 if (strcmp(argv[i], "--use_staging") == 0) {
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07003992 demo->use_staging_buffer = true;
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003993 continue;
Ian Elliott639ca472015-04-16 15:23:05 -06003994 }
Dave Houlton5fa47912018-02-16 11:02:26 -07003995 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
3996 demo->presentMode = atoi(argv[i + 1]);
Tony Barbour291d57b2016-10-21 14:47:07 -06003997 i++;
3998 continue;
3999 }
Courtney Goeltzenleuchter03f4b772015-07-22 11:03:51 -06004000 if (strcmp(argv[i], "--break") == 0) {
4001 demo->use_break = true;
4002 continue;
4003 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004004 if (strcmp(argv[i], "--validate") == 0) {
4005 demo->validate = true;
4006 continue;
4007 }
Tobin Ehlis4eb29d62017-03-14 11:29:01 -06004008 if (strcmp(argv[i], "--validate-checks-disabled") == 0) {
4009 demo->validate = true;
4010 demo->validate_checks_disabled = true;
4011 continue;
4012 }
Tony Barbour2593b182016-04-19 10:57:58 -06004013 if (strcmp(argv[i], "--xlib") == 0) {
Tony Barbour153cb062016-12-07 13:43:36 -07004014 fprintf(stderr, "--xlib is deprecated and no longer does anything");
Tony Barbour2593b182016-04-19 10:57:58 -06004015 continue;
4016 }
Dave Houlton5fa47912018-02-16 11:02:26 -07004017 if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && i < argc - 1 &&
4018 sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && demo->frameCount >= 0) {
David Pinedo2bb7c932015-06-18 17:03:14 -06004019 i++;
4020 continue;
4021 }
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +01004022 if (strcmp(argv[i], "--width") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->width) == 1 && demo->width > 0) {
4023 i++;
4024 continue;
4025 }
4026 if (strcmp(argv[i], "--height") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->height) == 1 && demo->height > 0) {
4027 i++;
4028 continue;
4029 }
lenny-lunargfbe22392016-06-06 11:07:53 -06004030 if (strcmp(argv[i], "--suppress_popups") == 0) {
4031 demo->suppress_popups = true;
4032 continue;
4033 }
Ian Elliottd940ca22017-03-22 08:31:27 -06004034 if (strcmp(argv[i], "--display_timing") == 0) {
4035 demo->VK_GOOGLE_display_timing_enabled = true;
4036 continue;
4037 }
Ian Elliott53622a72017-03-28 11:06:33 -06004038 if (strcmp(argv[i], "--incremental_present") == 0) {
4039 demo->VK_KHR_incremental_present_enabled = true;
4040 continue;
4041 }
Tony-LunarG50e737c2020-07-16 14:26:03 -06004042 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
4043 demo->gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +00004044 assert(demo->gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -06004045 i++;
4046 continue;
4047 }
Mark Young43c08f82021-11-30 16:38:25 -07004048 if (strcmp(argv[i], "--force_errors") == 0) {
4049 demo->force_errors = true;
4050 continue;
4051 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004052
Cody Northropaf28a532016-09-27 10:50:57 -06004053#if defined(ANDROID)
Lenny Komowffe446c2018-11-19 17:08:04 -07004054 ERR_EXIT("Usage: vkcube [--validate]\n", "Usage");
Cody Northropaf28a532016-09-27 10:50:57 -06004055#else
Tony-LunarGd74734f2019-06-04 14:11:43 -06004056 char *message =
4057 "Usage:\n %s\t[--use_staging] [--validate] [--validate-checks-disabled]\n"
4058 "\t[--break] [--c <framecount>] [--suppress_popups]\n"
4059 "\t[--incremental_present] [--display_timing]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -06004060 "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -06004061 "\t[--present_mode <present mode enum>]\n"
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +01004062 "\t[--width <width>] [--height <height>]\n"
Mark Young43c08f82021-11-30 16:38:25 -07004063 "\t[--force_errors]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -06004064 "\t<present_mode_enum>\n"
4065 "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = %d\n"
4066 "\t\tVK_PRESENT_MODE_MAILBOX_KHR = %d\n"
4067 "\t\tVK_PRESENT_MODE_FIFO_KHR = %d\n"
4068 "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = %d\n";
4069 int length = snprintf(NULL, 0, message, APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR,
4070 VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR);
4071 char *usage = (char *)malloc(length + 1);
4072 if (!usage) {
4073 exit(1);
4074 }
4075 snprintf(usage, length + 1, message, APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR,
4076 VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR);
4077#if defined(_WIN32)
4078 if (!demo->suppress_popups) MessageBox(NULL, usage, "Usage Error", MB_OK);
4079#else
Tony-LunarG122ac062019-06-13 16:21:57 -06004080 fprintf(stderr, "%s", usage);
Ian Elliott639ca472015-04-16 15:23:05 -06004081 fflush(stderr);
Tony-LunarGd74734f2019-06-04 14:11:43 -06004082#endif
4083 free(usage);
Ian Elliott639ca472015-04-16 15:23:05 -06004084 exit(1);
Cody Northropaf28a532016-09-27 10:50:57 -06004085#endif
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07004086 }
4087
Tony Barbour153cb062016-12-07 13:43:36 -07004088 demo_init_connection(demo);
Tony Barbour2593b182016-04-19 10:57:58 -06004089
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06004090 demo_init_vk(demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004091
Tony Barbour66a56c32016-09-21 13:10:56 -06004092 demo->spin_angle = 4.0f;
4093 demo->spin_increment = 0.2f;
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -06004094 demo->pause = false;
4095
Dave Houlton5fa47912018-02-16 11:02:26 -07004096 mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -06004097 mat4x4_look_at(demo->view_matrix, eye, origin, up);
4098 mat4x4_identity(demo->model_matrix);
Rene Lindsaybcccdea2016-08-12 17:56:09 -06004099
Dave Houlton5fa47912018-02-16 11:02:26 -07004100 demo->projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004101}
4102
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004103#if defined(VK_USE_PLATFORM_WIN32_KHR)
Mark Young418b9d12016-01-06 14:26:04 -07004104// Include header required for parsing the command line options.
4105#include <shellapi.h>
Ian Elliottf9cf78c2015-04-28 10:33:11 -06004106
Dave Houlton5fa47912018-02-16 11:02:26 -07004107int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
4108 MSG msg; // message
4109 bool done; // flag saying when app is complete
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004110 int argc;
Karl Schultze4dc75c2016-02-02 15:37:51 -07004111 char **argv;
Ian Elliott639ca472015-04-16 15:23:05 -06004112
Jamie Madillb2ff6502017-03-15 16:17:46 -04004113 // Ensure wParam is initialized.
4114 msg.wParam = 0;
4115
Karl Schultze4dc75c2016-02-02 15:37:51 -07004116 // Use the CommandLine functions to get the command line arguments.
4117 // Unfortunately, Microsoft outputs
4118 // this information as wide characters for Unicode, and we simply want the
4119 // Ascii version to be compatible
4120 // with the non-Windows side. So, we have to convert the information to
4121 // Ascii character strings.
4122 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
4123 if (NULL == commandLineArgs) {
Mark Young418b9d12016-01-06 14:26:04 -07004124 argc = 0;
4125 }
4126
Karl Schultze4dc75c2016-02-02 15:37:51 -07004127 if (argc > 0) {
4128 argv = (char **)malloc(sizeof(char *) * argc);
4129 if (argv == NULL) {
Mark Young418b9d12016-01-06 14:26:04 -07004130 argc = 0;
Karl Schultze4dc75c2016-02-02 15:37:51 -07004131 } else {
4132 for (int iii = 0; iii < argc; iii++) {
4133 size_t wideCharLen = wcslen(commandLineArgs[iii]);
Mark Young418b9d12016-01-06 14:26:04 -07004134 size_t numConverted = 0;
4135
Karl Schultze4dc75c2016-02-02 15:37:51 -07004136 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
4137 if (argv[iii] != NULL) {
Dave Houlton5fa47912018-02-16 11:02:26 -07004138 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Mark Young418b9d12016-01-06 14:26:04 -07004139 }
4140 }
4141 }
Karl Schultze4dc75c2016-02-02 15:37:51 -07004142 } else {
Mark Young418b9d12016-01-06 14:26:04 -07004143 argv = NULL;
4144 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004145
4146 demo_init(&demo, argc, argv);
Mark Young418b9d12016-01-06 14:26:04 -07004147
4148 // Free up the items we had to allocate for the command line arguments.
Karl Schultze4dc75c2016-02-02 15:37:51 -07004149 if (argc > 0 && argv != NULL) {
4150 for (int iii = 0; iii < argc; iii++) {
4151 if (argv[iii] != NULL) {
Mark Young418b9d12016-01-06 14:26:04 -07004152 free(argv[iii]);
4153 }
4154 }
4155 free(argv);
4156 }
4157
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004158 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07004159 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Ian Elliott639ca472015-04-16 15:23:05 -06004160 demo_create_window(&demo);
Tony Barbourcc69f452015-10-08 13:59:42 -06004161 demo_init_vk_swapchain(&demo);
Ian Elliott639ca472015-04-16 15:23:05 -06004162
4163 demo_prepare(&demo);
4164
Dave Houlton5fa47912018-02-16 11:02:26 -07004165 done = false; // initialize loop condition variable
Mark Young418b9d12016-01-06 14:26:04 -07004166
4167 // main message loop
Karl Schultze4dc75c2016-02-02 15:37:51 -07004168 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01004169 if (demo.pause) {
4170 const BOOL succ = WaitMessage();
4171
4172 if (!succ) {
4173 struct demo *tmp = &demo;
4174 struct demo *demo = tmp;
4175 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
4176 }
4177 }
Ian Elliotta748eaf2015-04-28 15:50:36 -06004178 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
Dave Houlton5fa47912018-02-16 11:02:26 -07004179 if (msg.message == WM_QUIT) // check for a quit message
Ian Elliott639ca472015-04-16 15:23:05 -06004180 {
Dave Houlton5fa47912018-02-16 11:02:26 -07004181 done = true; // if found, quit app
Karl Schultze4dc75c2016-02-02 15:37:51 -07004182 } else {
Ian Elliott639ca472015-04-16 15:23:05 -06004183 /* Translate and dispatch to event queue*/
Karl Schultze4dc75c2016-02-02 15:37:51 -07004184 TranslateMessage(&msg);
Ian Elliott639ca472015-04-16 15:23:05 -06004185 DispatchMessage(&msg);
4186 }
Tony Barbourc8a59892015-10-20 12:49:46 -06004187 RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT);
Ian Elliott639ca472015-04-16 15:23:05 -06004188 }
4189
4190 demo_cleanup(&demo);
4191
Karl Schultze4dc75c2016-02-02 15:37:51 -07004192 return (int)msg.wParam;
Ian Elliott639ca472015-04-16 15:23:05 -06004193}
Bill Hollingsf4352142017-02-14 22:58:56 -05004194
Bill Hollings0a0625a2019-07-15 17:39:18 -04004195#elif defined(VK_USE_PLATFORM_METAL_EXT)
4196static void demo_main(struct demo *demo, void *caMetalLayer, int argc, const char *argv[]) {
Dave Houlton5fa47912018-02-16 11:02:26 -07004197 demo_init(demo, argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04004198 demo->caMetalLayer = caMetalLayer;
Tony Barbourc65cd752017-03-13 15:29:35 -06004199 demo_init_vk_swapchain(demo);
4200 demo_prepare(demo);
4201 demo->spin_angle = 0.4f;
Bill Hollingsf4352142017-02-14 22:58:56 -05004202}
4203
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004204#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
4205#include <android/log.h>
4206#include <android_native_app_glue.h>
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004207#include "android_util.h"
4208
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004209static bool initialized = false;
4210static bool active = false;
4211struct demo demo;
4212
Dave Houlton5fa47912018-02-16 11:02:26 -07004213static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004214
Dave Houlton5fa47912018-02-16 11:02:26 -07004215static void processCommand(struct android_app *app, int32_t cmd) {
4216 switch (cmd) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004217 case APP_CMD_INIT_WINDOW: {
4218 if (app->window) {
Ian Elliottf05d5d12016-05-17 12:03:35 -06004219 // We're getting a new window. If the app is starting up, we
4220 // need to initialize. If the app has already been
4221 // initialized, that means that we lost our previous window,
4222 // which means that we have a lot of work to do. At a minimum,
4223 // we need to destroy the swapchain and surface associated with
4224 // the old window, and create a new surface and swapchain.
4225 // However, since there are a lot of other objects/state that
4226 // is tied to the swapchain, it's easiest to simply cleanup and
4227 // start over (i.e. use a brute-force approach of re-starting
4228 // the app)
4229 if (demo.prepared) {
4230 demo_cleanup(&demo);
4231 }
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004232
4233 // Parse Intents into argc, argv
4234 // Use the following key to send arguments, i.e.
4235 // --es args "--validate"
4236 const char key[] = "args";
Dave Houlton5fa47912018-02-16 11:02:26 -07004237 char *appTag = (char *)APP_SHORT_NAME;
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004238 int argc = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07004239 char **argv = get_args(app, key, appTag, &argc);
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004240
4241 __android_log_print(ANDROID_LOG_INFO, appTag, "argc = %i", argc);
Dave Houlton5fa47912018-02-16 11:02:26 -07004242 for (int i = 0; i < argc; i++) __android_log_print(ANDROID_LOG_INFO, appTag, "argv[%i] = %s", i, argv[i]);
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004243
4244 demo_init(&demo, argc, argv);
4245
4246 // Free the argv malloc'd by get_args
Dave Houlton5fa47912018-02-16 11:02:26 -07004247 for (int i = 0; i < argc; i++) free(argv[i]);
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004248
Dave Houlton5fa47912018-02-16 11:02:26 -07004249 demo.window = (void *)app->window;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004250 demo_init_vk_swapchain(&demo);
4251 demo_prepare(&demo);
4252 initialized = true;
4253 }
4254 break;
4255 }
4256 case APP_CMD_GAINED_FOCUS: {
4257 active = true;
4258 break;
4259 }
4260 case APP_CMD_LOST_FOCUS: {
4261 active = false;
4262 break;
4263 }
4264 }
4265}
4266
Dave Houlton5fa47912018-02-16 11:02:26 -07004267void android_main(struct android_app *app) {
Cody Northrop8707a6e2016-04-26 19:59:19 -06004268#ifdef ANDROID
4269 int vulkanSupport = InitVulkan();
Dave Houlton5fa47912018-02-16 11:02:26 -07004270 if (vulkanSupport == 0) return;
Cody Northrop8707a6e2016-04-26 19:59:19 -06004271#endif
4272
Ian Elliottf05d5d12016-05-17 12:03:35 -06004273 demo.prepared = false;
4274
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004275 app->onAppCmd = processCommand;
4276 app->onInputEvent = processInput;
4277
Dave Houlton5fa47912018-02-16 11:02:26 -07004278 while (1) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004279 int events;
Dave Houlton5fa47912018-02-16 11:02:26 -07004280 struct android_poll_source *source;
4281 while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004282 if (source) {
4283 source->process(app, source);
4284 }
4285
4286 if (app->destroyRequested != 0) {
4287 demo_cleanup(&demo);
4288 return;
4289 }
4290 }
4291 if (initialized && active) {
4292 demo_run(&demo);
4293 }
4294 }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004295}
Tobin Ehlis43ed2982016-04-28 10:17:33 -06004296#else
Karl Schultze4dc75c2016-02-02 15:37:51 -07004297int main(int argc, char **argv) {
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004298 struct demo demo;
4299
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07004300 demo_init(&demo, argc, argv);
Tony Barbour153cb062016-12-07 13:43:36 -07004301#if defined(VK_USE_PLATFORM_XCB_KHR)
Tony Barbour8295ac42016-08-08 11:04:17 -06004302 demo_create_xcb_window(&demo);
4303#elif defined(VK_USE_PLATFORM_XLIB_KHR)
4304 demo_create_xlib_window(&demo);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09004305#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
4306 demo_create_window(&demo);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02004307#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
4308 demo_create_directfb_window(&demo);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09004309#endif
Tony Barbour2593b182016-04-19 10:57:58 -06004310
Tony Barbourcc69f452015-10-08 13:59:42 -06004311 demo_init_vk_swapchain(&demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004312
4313 demo_prepare(&demo);
Tony Barbour2593b182016-04-19 10:57:58 -06004314
Tony Barbour153cb062016-12-07 13:43:36 -07004315#if defined(VK_USE_PLATFORM_XCB_KHR)
Tony Barbour8295ac42016-08-08 11:04:17 -06004316 demo_run_xcb(&demo);
4317#elif defined(VK_USE_PLATFORM_XLIB_KHR)
4318 demo_run_xlib(&demo);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09004319#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
4320 demo_run(&demo);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02004321#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
4322 demo_run_directfb(&demo);
Damien Leone600c3052017-01-31 10:26:07 -07004323#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
4324 demo_run_display(&demo);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09004325#endif
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004326
4327 demo_cleanup(&demo);
4328
Karl Schultz0218c002016-03-22 17:06:13 -06004329 return validation_error;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004330}
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004331#endif