-
Notifications
You must be signed in to change notification settings - Fork 158
/
cube.cpp
3890 lines (3418 loc) · 154 KB
/
cube.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015-2019 The Khronos Group Inc.
* Copyright (c) 2015-2019 Valve Corporation
* Copyright (c) 2015-2019 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Jeremy Hayes <[email protected]>
* Author: Charles Giessen <[email protected]>
*/
#include <cassert>
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <csignal>
#include <sstream>
#include <iostream>
#include <memory>
#if defined(VK_USE_PLATFORM_XLIB_KHR)
#include "xlib_loader.h"
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
#include "xcb_loader.h"
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
#include <linux/input.h>
#include "wayland_loader.h"
#endif
#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
#define VULKAN_HPP_NO_EXCEPTIONS
#define VULKAN_HPP_TYPESAFE_CONVERSION 1
// Volk requires VK_NO_PROTOTYPES before including vulkan.hpp
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.hpp>
#define VOLK_IMPLEMENTATION
#include "volk.h"
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
#include "linmath.h"
#ifndef NDEBUG
#define VERIFY(x) assert(x)
#else
#define VERIFY(x) ((void)(x))
#endif
#define APP_SHORT_NAME "vkcubepp"
// Allow a maximum of two outstanding presentation operations.
constexpr uint32_t FRAME_LAG = 2;
#ifdef _WIN32
#define ERR_EXIT(err_msg, err_class) \
do { \
if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
exit(1); \
} while (0)
#else
#define ERR_EXIT(err_msg, err_class) \
do { \
printf("%s\n", err_msg); \
fflush(stdout); \
exit(1); \
} while (0)
#endif
struct texture_object {
vk::Sampler sampler;
vk::Image image;
vk::Buffer buffer;
vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
vk::MemoryAllocateInfo mem_alloc;
vk::DeviceMemory mem;
vk::ImageView view;
uint32_t tex_width{0};
uint32_t tex_height{0};
};
static char const *const tex_files[] = {"lunarg.ppm"};
static int validation_error = 0;
struct vktexcube_vs_uniform {
// Must start with MVP
float mvp[4][4];
float position[12 * 3][4];
float attr[12 * 3][4];
};
//--------------------------------------------------------------------------------------
// Mesh and VertexFormat Data
//--------------------------------------------------------------------------------------
// clang-format off
static const float g_vertex_buffer_data[] = {
-1.0f,-1.0f,-1.0f, // -X side
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f, // -Z side
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f, // -Y side
1.0f,-1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f,-1.0f, // +Y side
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
1.0f, 1.0f,-1.0f, // +X side
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f, // +Z side
-1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
};
static const float g_uv_buffer_data[] = {
0.0f, 1.0f, // -X side
1.0f, 1.0f,
1.0f, 0.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f, // -Z side
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
1.0f, 0.0f, // -Y side
1.0f, 1.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f, // +Y side
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f, // +X side
0.0f, 0.0f,
0.0f, 1.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f, // +Z side
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
};
// clang-format on
enum class WsiPlatform {
auto_ = 0,
win32,
metal,
android,
qnx,
xcb,
xlib,
wayland,
directfb,
display,
invalid, // Sentinel just to indicate invalid user input
};
WsiPlatform wsi_from_string(std::string const &str) {
if (str == "auto") return WsiPlatform::auto_;
#if defined(VK_USE_PLATFORM_WIN32_KHR)
if (str == "win32") return WsiPlatform::win32;
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
if (str == "metal") return WsiPlatform::metal;
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (str == "android") return WsiPlatform::android;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
if (str == "qnx") return WsiPlatform::qnx;
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (str == "xcb") return WsiPlatform::xcb;
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (str == "xlib") return WsiPlatform::xlib;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (str == "wayland") return WsiPlatform::wayland;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (str == "directfb") return WsiPlatform::directfb;
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
if (str == "display") return WsiPlatform::display;
#endif
return WsiPlatform::invalid;
};
const char *wsi_to_string(WsiPlatform wsi_platform) {
switch (wsi_platform) {
case (WsiPlatform::auto_):
return "auto";
#if defined(VK_USE_PLATFORM_WIN32_KHR)
case (WsiPlatform::win32):
return "win32";
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
case (WsiPlatform::metal):
return "metal";
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
case (WsiPlatform::android):
return "android";
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
case (WsiPlatform::qnx):
return "qnx";
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
case (WsiPlatform::xcb):
return "xcb";
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
case (WsiPlatform::xlib):
return "xlib";
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
case (WsiPlatform::wayland):
return "wayland";
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
case (WsiPlatform::directfb):
return "directfb";
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
case (WsiPlatform::display):
return "display";
#endif
default:
return "unknown";
}
};
struct SwapchainImageResources {
vk::Image image;
vk::CommandBuffer cmd;
vk::CommandBuffer graphics_to_present_cmd;
vk::ImageView view;
vk::Buffer uniform_buffer;
vk::DeviceMemory uniform_memory;
void *uniform_memory_ptr = nullptr;
vk::Framebuffer framebuffer;
vk::DescriptorSet descriptor_set;
};
struct Demo {
void build_image_ownership_cmd(const SwapchainImageResources &swapchain_image_resource);
vk::Bool32 check_layers(const std::vector<const char *> &check_names, const std::vector<vk::LayerProperties> &layers);
void cleanup();
void destroy_swapchain_related_resources();
void create_device();
void destroy_texture(texture_object &tex_objs);
void draw();
void draw_build_cmd(const SwapchainImageResources &swapchain_image_resource);
void prepare_init_cmd();
void flush_init_cmd();
void init(int argc, char **argv);
void check_and_set_wsi_platform();
void init_vk();
void init_vk_swapchain();
void prepare();
void prepare_buffers();
void prepare_cube_data_buffers();
void prepare_depth();
void prepare_descriptor_layout();
void prepare_descriptor_pool();
void prepare_descriptor_set();
void prepare_framebuffers();
vk::ShaderModule prepare_shader_module(const uint32_t *code, size_t size);
vk::ShaderModule prepare_vs();
vk::ShaderModule prepare_fs();
void prepare_pipeline();
void prepare_render_pass();
void prepare_texture_image(const char *filename, texture_object &tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
vk::MemoryPropertyFlags required_props);
void prepare_texture_buffer(const char *filename, texture_object &tex_obj);
void prepare_textures();
void resize();
void create_surface();
void set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages);
void update_data_buffer();
bool loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout &layout, uint32_t &width, uint32_t &height);
bool memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t &typeIndex);
vk::SurfaceFormatKHR pick_surface_format(const std::vector<vk::SurfaceFormatKHR> &surface_formats);
static VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
void *pUserData);
#if defined(VK_USE_PLATFORM_WIN32_KHR)
void run();
void create_window();
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
const char *init_xlib_connection();
void create_xlib_window();
void handle_xlib_event(const XEvent *event);
void run_xlib();
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
const char *init_xcb_connection();
void handle_xcb_event(const xcb_generic_event_t *event);
void run_xcb();
void create_xcb_window();
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
const char *init_wayland_connection();
void run_wayland();
void create_wayland_window();
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
void handle_directfb_event(const DFBInputEvent *event);
void run_directfb();
void create_directfb_window();
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
void run();
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
vk::Result create_display_surface();
void run_display();
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
void run();
void create_window();
#endif
std::string name = "vkcubepp"; // Name to put on the window/icon
#if defined(VK_USE_PLATFORM_WIN32_KHR)
HINSTANCE connection = nullptr; // hInstance - Windows Instance
HWND window = nullptr; // hWnd - window handle
POINT minsize = {0, 0}; // minimum window size
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
void *xlib_library;
Window xlib_window = 0;
Atom xlib_wm_delete_window = 0;
Display *xlib_display = nullptr;
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
void *xcb_library;
xcb_window_t xcb_window = 0;
xcb_screen_t *screen = nullptr;
xcb_connection_t *connection = nullptr;
xcb_intern_atom_reply_t *atom_wm_delete_window = nullptr;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
void *wayland_library = nullptr;
wl_display *wayland_display = nullptr;
wl_registry *registry = nullptr;
wl_compositor *compositor = nullptr;
wl_surface *wayland_window = nullptr;
xdg_wm_base *wm_base = nullptr;
zxdg_decoration_manager_v1 *xdg_decoration_mgr = nullptr;
zxdg_toplevel_decoration_v1 *toplevel_decoration = nullptr;
xdg_surface *window_surface = nullptr;
bool xdg_surface_has_been_configured = false;
xdg_toplevel *window_toplevel = nullptr;
wl_seat *seat = nullptr;
wl_pointer *pointer = nullptr;
wl_keyboard *keyboard = nullptr;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
IDirectFB *dfb = nullptr;
IDirectFBSurface *directfb_window = nullptr;
IDirectFBEventBuffer *event_buffer = nullptr;
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
void *caMetalLayer;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
screen_context_t screen_context = nullptr;
screen_window_t screen_window = nullptr;
screen_event_t screen_event = nullptr;
#endif
WsiPlatform wsi_platform = WsiPlatform::auto_;
vk::SurfaceKHR surface;
bool prepared = false;
bool use_staging_buffer = false;
bool separate_present_queue = false;
bool invalid_gpu_selection = false;
int32_t gpu_number = 0;
vk::Instance inst;
vk::DebugUtilsMessengerEXT debug_messenger;
vk::PhysicalDevice gpu;
vk::Device device;
vk::Queue graphics_queue;
vk::Queue present_queue;
uint32_t graphics_queue_family_index = 0;
uint32_t present_queue_family_index = 0;
std::array<vk::Semaphore, FRAME_LAG> image_acquired_semaphores;
std::array<vk::Semaphore, FRAME_LAG> draw_complete_semaphores;
std::array<vk::Semaphore, FRAME_LAG> image_ownership_semaphores;
vk::PhysicalDeviceProperties gpu_props;
std::vector<vk::QueueFamilyProperties> queue_props;
vk::PhysicalDeviceMemoryProperties memory_properties;
std::vector<const char *> enabled_instance_extensions;
std::vector<const char *> enabled_layers;
std::vector<const char *> enabled_device_extensions;
uint32_t width = 0;
uint32_t height = 0;
vk::Format format;
vk::ColorSpaceKHR color_space;
vk::SwapchainKHR swapchain;
std::vector<SwapchainImageResources> swapchain_image_resources;
vk::PresentModeKHR presentMode = vk::PresentModeKHR::eFifo;
std::array<vk::Fence, FRAME_LAG> fences;
uint32_t frame_index = 0;
vk::CommandPool cmd_pool;
vk::CommandPool present_cmd_pool;
struct {
vk::Format format;
vk::Image image;
vk::MemoryAllocateInfo mem_alloc;
vk::DeviceMemory mem;
vk::ImageView view;
} depth;
static int32_t const texture_count = 1;
std::array<texture_object, texture_count> textures;
texture_object staging_texture;
struct {
vk::Buffer buf;
vk::MemoryAllocateInfo mem_alloc;
vk::DeviceMemory mem;
vk::DescriptorBufferInfo buffer_info;
} uniform_data;
vk::CommandBuffer cmd; // Buffer for initialization commands
vk::PipelineLayout pipeline_layout;
vk::DescriptorSetLayout desc_layout;
vk::PipelineCache pipelineCache;
vk::RenderPass render_pass;
vk::Pipeline pipeline;
mat4x4 projection_matrix = {};
mat4x4 view_matrix = {};
mat4x4 model_matrix = {};
float spin_angle = 0.0f;
float spin_increment = 0.0f;
bool pause = false;
vk::ShaderModule vert_shader_module;
vk::ShaderModule frag_shader_module;
vk::DescriptorPool desc_pool;
vk::DescriptorSet desc_set;
std::vector<vk::Framebuffer> framebuffers;
bool quit = false;
uint32_t curFrame = 0;
uint32_t frameCount = 0;
bool validate = false;
bool in_callback = false;
bool use_debug_messenger = false;
bool use_break = false;
bool suppress_popups = false;
bool force_errors = false;
bool is_minimized = false;
uint32_t current_buffer = 0;
};
#ifdef _WIN32
// MS-Windows event handling function:
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
wl_fixed_t sy) {}
static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
uint32_t state) {
Demo &demo = *static_cast<Demo *>(data);
if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
xdg_toplevel_move(demo.window_toplevel, demo.seat, serial);
}
}
static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
static const struct wl_pointer_listener pointer_listener = {
pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
};
static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
struct wl_array *keys) {}
static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
uint32_t state) {
if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
Demo &demo = *static_cast<Demo *>(data);
switch (key) {
case KEY_ESC: // Escape
demo.quit = true;
break;
case KEY_LEFT: // left arrow key
demo.spin_angle -= demo.spin_increment;
break;
case KEY_RIGHT: // right arrow key
demo.spin_angle += demo.spin_increment;
break;
case KEY_SPACE: // space bar
demo.pause = !demo.pause;
break;
}
}
static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
static const struct wl_keyboard_listener keyboard_listener = {
keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
};
static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
// Subscribe to pointer events
Demo &demo = *static_cast<Demo *>(data);
if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo.pointer) {
demo.pointer = wl_seat_get_pointer(seat);
wl_pointer_add_listener(demo.pointer, &pointer_listener, &demo);
} else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo.pointer) {
wl_pointer_destroy(demo.pointer);
demo.pointer = nullptr;
}
// Subscribe to keyboard events
if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
demo.keyboard = wl_seat_get_keyboard(seat);
wl_keyboard_add_listener(demo.keyboard, &keyboard_listener, &demo);
} else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && demo.keyboard) {
wl_keyboard_destroy(demo.keyboard);
demo.keyboard = nullptr;
}
}
static const wl_seat_listener seat_listener = {
seat_handle_capabilities,
};
static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
Demo &demo = *static_cast<Demo *>(data);
// pickup wayland objects when they appear
if (strcmp(interface, wl_compositor_interface.name) == 0) {
demo.compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
} else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
demo.wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
xdg_wm_base_add_listener(demo.wm_base, &wm_base_listener, nullptr);
} else if (strcmp(interface, wl_seat_interface.name) == 0) {
demo.seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
wl_seat_add_listener(demo.seat, &seat_listener, &demo);
} else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
demo.xdg_decoration_mgr =
(zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
}
}
static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
#endif
void Demo::build_image_ownership_cmd(const SwapchainImageResources &swapchain_image_resource) {
auto result = swapchain_image_resource.graphics_to_present_cmd.begin(
vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse));
VERIFY(result == vk::Result::eSuccess);
auto const image_ownership_barrier =
vk::ImageMemoryBarrier()
.setSrcAccessMask(vk::AccessFlags())
.setDstAccessMask(vk::AccessFlags())
.setOldLayout(vk::ImageLayout::ePresentSrcKHR)
.setNewLayout(vk::ImageLayout::ePresentSrcKHR)
.setSrcQueueFamilyIndex(graphics_queue_family_index)
.setDstQueueFamilyIndex(present_queue_family_index)
.setImage(swapchain_image_resource.image)
.setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
swapchain_image_resource.graphics_to_present_cmd.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe,
vk::PipelineStageFlagBits::eBottomOfPipe,
vk::DependencyFlagBits(), {}, {}, image_ownership_barrier);
result = swapchain_image_resource.graphics_to_present_cmd.end();
VERIFY(result == vk::Result::eSuccess);
}
vk::Bool32 Demo::check_layers(const std::vector<const char *> &check_names, const std::vector<vk::LayerProperties> &layers) {
for (const auto &name : check_names) {
vk::Bool32 found = VK_FALSE;
for (const auto &layer : layers) {
if (!strcmp(name, layer.layerName)) {
found = VK_TRUE;
break;
}
}
if (!found) {
fprintf(stderr, "Cannot find layer: %s\n", name);
return 0;
}
}
return VK_TRUE;
}
void Demo::cleanup() {
prepared = false;
auto result = device.waitIdle();
VERIFY(result == vk::Result::eSuccess);
if (!is_minimized) {
destroy_swapchain_related_resources();
}
// Wait for fences from present operations
for (uint32_t i = 0; i < FRAME_LAG; i++) {
device.destroyFence(fences[i]);
device.destroySemaphore(image_acquired_semaphores[i]);
device.destroySemaphore(draw_complete_semaphores[i]);
if (separate_present_queue) {
device.destroySemaphore(image_ownership_semaphores[i]);
}
}
device.destroySwapchainKHR(swapchain);
device.destroy();
inst.destroySurfaceKHR(surface);
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (wsi_platform == WsiPlatform::xlib) {
XDestroyWindow(xlib_display, xlib_window);
XCloseDisplay(xlib_display);
}
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (wsi_platform == WsiPlatform::xcb) {
xcb_destroy_window(connection, xcb_window);
xcb_disconnect(connection);
free(atom_wm_delete_window);
}
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (wsi_platform == WsiPlatform::wayland) {
if (keyboard) wl_keyboard_destroy(keyboard);
if (pointer) wl_pointer_destroy(pointer);
if (seat) wl_seat_destroy(seat);
xdg_toplevel_destroy(window_toplevel);
xdg_surface_destroy(window_surface);
wl_surface_destroy(wayland_window);
xdg_wm_base_destroy(wm_base);
if (xdg_decoration_mgr) {
zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
}
wl_compositor_destroy(compositor);
wl_registry_destroy(registry);
wl_display_disconnect(wayland_display);
}
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (wsi_platform == WsiPlatform::directfb) {
event_buffer->Release(event_buffer);
directfb_window->Release(directfb_window);
dfb->Release(dfb);
}
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
screen_destroy_event(screen_event);
screen_destroy_window(screen_window);
screen_destroy_context(screen_context);
#endif
if (use_debug_messenger) {
inst.destroyDebugUtilsMessengerEXT(debug_messenger);
}
inst.destroy();
}
void Demo::create_device() {
float priorities = 0.0;
std::vector<vk::DeviceQueueCreateInfo> queues;
queues.push_back(vk::DeviceQueueCreateInfo().setQueueFamilyIndex(graphics_queue_family_index).setQueuePriorities(priorities));
if (separate_present_queue) {
queues.push_back(
vk::DeviceQueueCreateInfo().setQueueFamilyIndex(present_queue_family_index).setQueuePriorities(priorities));
}
auto deviceInfo = vk::DeviceCreateInfo().setQueueCreateInfos(queues).setPEnabledExtensionNames(enabled_device_extensions);
auto device_return = gpu.createDevice(deviceInfo);
VERIFY(device_return.result == vk::Result::eSuccess);
device = device_return.value;
VULKAN_HPP_DEFAULT_DISPATCHER.init(device);
}
void Demo::destroy_texture(texture_object &tex_objs) {
// clean up staging resources
device.freeMemory(tex_objs.mem);
if (tex_objs.image) device.destroyImage(tex_objs.image);
if (tex_objs.buffer) device.destroyBuffer(tex_objs.buffer);
}
void Demo::draw() {
// Ensure no more than FRAME_LAG renderings are outstanding
const vk::Result wait_result = device.waitForFences(fences[frame_index], VK_TRUE, UINT64_MAX);
VERIFY(wait_result == vk::Result::eSuccess || wait_result == vk::Result::eTimeout);
device.resetFences({fences[frame_index]});
vk::Result acquire_result;
do {
acquire_result =
device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), ¤t_buffer);
if (acquire_result == vk::Result::eErrorOutOfDateKHR) {
// demo.swapchain is out of date (e.g. the window was resized) and
// must be recreated:
resize();
} else if (acquire_result == vk::Result::eSuboptimalKHR) {
// swapchain is not as optimal as it could be, but the platform's
// presentation engine will still present the image correctly.
break;
} else if (acquire_result == vk::Result::eErrorSurfaceLostKHR) {
inst.destroySurfaceKHR(surface);
create_surface();
resize();
} else {
VERIFY(acquire_result == vk::Result::eSuccess);
}
} while (acquire_result != vk::Result::eSuccess);
update_data_buffer();
// Wait for the image acquired semaphore to be signaled to ensure
// that the image won't be rendered to until the presentation
// engine has fully released ownership to the application, and it is
// okay to render to the image.
vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
auto submit_result = graphics_queue.submit(vk::SubmitInfo()
.setWaitDstStageMask(pipe_stage_flags)
.setWaitSemaphores(image_acquired_semaphores[frame_index])
.setCommandBuffers(swapchain_image_resources[current_buffer].cmd)
.setSignalSemaphores(draw_complete_semaphores[frame_index]),
fences[frame_index]);
VERIFY(submit_result == vk::Result::eSuccess);
if (separate_present_queue) {
// If we are using separate queues, change image ownership to the
// present queue before presenting, waiting for the draw complete
// semaphore and signalling the ownership released semaphore when
// finished
auto change_owner_result =
present_queue.submit(vk::SubmitInfo()
.setWaitDstStageMask(pipe_stage_flags)
.setWaitSemaphores(draw_complete_semaphores[frame_index])
.setCommandBuffers(swapchain_image_resources[current_buffer].graphics_to_present_cmd)
.setSignalSemaphores(image_ownership_semaphores[frame_index]));
VERIFY(change_owner_result == vk::Result::eSuccess);
}
const auto presentInfo = vk::PresentInfoKHR()
.setWaitSemaphores(separate_present_queue ? image_ownership_semaphores[frame_index]
: draw_complete_semaphores[frame_index])
.setSwapchains(swapchain)
.setImageIndices(current_buffer);
// If we are using separate queues we have to wait for image ownership,
// otherwise wait for draw complete
auto present_result = present_queue.presentKHR(&presentInfo);
frame_index += 1;
frame_index %= FRAME_LAG;
if (present_result == vk::Result::eErrorOutOfDateKHR) {
// swapchain is out of date (e.g. the window was resized) and
// must be recreated:
resize();
} else if (present_result == vk::Result::eSuboptimalKHR) {
// SUBOPTIMAL could be due to resize
vk::SurfaceCapabilitiesKHR surfCapabilities;
auto caps_result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
VERIFY(caps_result == vk::Result::eSuccess);
if (surfCapabilities.currentExtent.width != width || surfCapabilities.currentExtent.height != height) {
resize();
}
} else if (present_result == vk::Result::eErrorSurfaceLostKHR) {
inst.destroySurfaceKHR(surface);
create_surface();
resize();
} else {
VERIFY(present_result == vk::Result::eSuccess);
}
}
void Demo::draw_build_cmd(const SwapchainImageResources &swapchain_image_resource) {
const auto commandBuffer = swapchain_image_resource.cmd;
vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
vk::ClearDepthStencilValue(1.0f, 0u)};
auto result = commandBuffer.begin(vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse));
VERIFY(result == vk::Result::eSuccess);
commandBuffer.beginRenderPass(vk::RenderPassBeginInfo()
.setRenderPass(render_pass)
.setFramebuffer(swapchain_image_resource.framebuffer)
.setRenderArea(vk::Rect2D(vk::Offset2D{}, vk::Extent2D(width, height)))
.setClearValueCount(2)
.setPClearValues(clearValues),
vk::SubpassContents::eInline);
commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, swapchain_image_resource.descriptor_set,
{});
float viewport_dimension;
float viewport_x = 0.0f;
float viewport_y = 0.0f;
if (width < height) {
viewport_dimension = static_cast<float>(width);
viewport_y = (height - width) / 2.0f;
} else {
viewport_dimension = static_cast<float>(height);
viewport_x = (width - height) / 2.0f;
}
commandBuffer.setViewport(0, vk::Viewport()
.setX(viewport_x)
.setY(viewport_y)
.setWidth(viewport_dimension)
.setHeight(viewport_dimension)
.setMinDepth(0.0f)
.setMaxDepth(1.0f));
commandBuffer.setScissor(0, vk::Rect2D(vk::Offset2D{}, vk::Extent2D(width, height)));
commandBuffer.draw(12 * 3, 1, 0, 0);
// Note that ending the renderpass changes the image's layout from
// COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
commandBuffer.endRenderPass();
if (separate_present_queue) {
// We have to transfer ownership from the graphics queue family to
// the
// present queue family to be able to present. Note that we don't
// have
// to transfer from present queue family back to graphics queue
// family at
// the start of the next frame because we don't care about the
// image's
// contents at that point.
commandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), {}, {},
vk::ImageMemoryBarrier()
.setSrcAccessMask(vk::AccessFlags())
.setDstAccessMask(vk::AccessFlags())
.setOldLayout(vk::ImageLayout::ePresentSrcKHR)
.setNewLayout(vk::ImageLayout::ePresentSrcKHR)
.setSrcQueueFamilyIndex(graphics_queue_family_index)
.setDstQueueFamilyIndex(present_queue_family_index)
.setImage(swapchain_image_resource.image)
.setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)));
}
result = commandBuffer.end();
VERIFY(result == vk::Result::eSuccess);
}
void Demo::prepare_init_cmd() {
auto cmd_pool_return = device.createCommandPool(vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index));
VERIFY(cmd_pool_return.result == vk::Result::eSuccess);
cmd_pool = cmd_pool_return.value;
auto cmd_return = device.allocateCommandBuffers(vk::CommandBufferAllocateInfo()
.setCommandPool(cmd_pool)
.setLevel(vk::CommandBufferLevel::ePrimary)
.setCommandBufferCount(1));
VERIFY(cmd_return.result == vk::Result::eSuccess);
cmd = cmd_return.value[0];
auto result = cmd.begin(vk::CommandBufferBeginInfo());
VERIFY(result == vk::Result::eSuccess);
}
void Demo::flush_init_cmd() {
auto result = cmd.end();
VERIFY(result == vk::Result::eSuccess);
auto fenceInfo = vk::FenceCreateInfo();
if (force_errors) {
// Remove sType to intentionally force validation layer errors.
fenceInfo.sType = vk::StructureType::eRenderPassBeginInfo;
}
auto fence_return = device.createFence(fenceInfo);
VERIFY(fence_return.result == vk::Result::eSuccess);
auto fence = fence_return.value;
result = graphics_queue.submit(vk::SubmitInfo().setCommandBuffers(cmd), fence);
VERIFY(result == vk::Result::eSuccess);
result = device.waitForFences(fence, VK_TRUE, UINT64_MAX);
VERIFY(result == vk::Result::eSuccess);
device.freeCommandBuffers(cmd_pool, cmd);
device.destroyFence(fence);
}
void Demo::init(int argc, char **argv) {
vec3 eye = {0.0f, 3.0f, 5.0f};
vec3 origin = {0, 0, 0};
vec3 up = {0.0f, 1.0f, 0.0};
presentMode = vk::PresentModeKHR::eFifo;
frameCount = UINT32_MAX;
width = 500;
height = 500;
/* Autodetect suitable / best GPU by default */
gpu_number = -1;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--use_staging") == 0) {
use_staging_buffer = true;
continue;
}
if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {