2 * Copyright (c) 2015-2016 The Khronos Group Inc.
3 * Copyright (c) 2015-2016 Valve Corporation
4 * Copyright (c) 2015-2016 LunarG, Inc.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Author: Jeremy Hayes <jeremy@lunarg.com>
21 #if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
22 #include <X11/Xutil.h>
23 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
24 #include <linux/input.h>
35 #if defined(VK_USE_PLATFORM_MIR_KHR)
36 #warning "Cubepp does not have code for Mir at this time"
39 #define VULKAN_HPP_NO_SMART_HANDLE
40 #define VULKAN_HPP_NO_EXCEPTIONS
41 #include <vulkan/vulkan.hpp>
42 #include <vulkan/vk_sdk_platform.h>
47 #define VERIFY(x) assert(x)
49 #define VERIFY(x) ((void)(x))
52 #define APP_SHORT_NAME "cube"
54 #define APP_NAME_STR_LEN 80
57 // Allow a maximum of two outstanding presentation operations.
60 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
63 #define ERR_EXIT(err_msg, err_class) \
65 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
69 #define ERR_EXIT(err_msg, err_class) \
71 printf("%s\n", err_msg); \
77 struct texture_object {
81 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
83 vk::MemoryAllocateInfo mem_alloc;
88 int32_t tex_height{0};
91 static char const *const tex_files[] = {"lunarg.ppm"};
93 static int validation_error = 0;
95 struct vkcube_vs_uniform {
96 // Must start with MVP
98 float position[12 * 3][4];
99 float color[12 * 3][4];
102 struct vktexcube_vs_uniform {
103 // Must start with MVP
105 float position[12 * 3][4];
106 float attr[12 * 3][4];
109 //--------------------------------------------------------------------------------------
110 // Mesh and VertexFormat Data
111 //--------------------------------------------------------------------------------------
113 static const float g_vertex_buffer_data[] = {
114 -1.0f,-1.0f,-1.0f, // -X side
121 -1.0f,-1.0f,-1.0f, // -Z side
128 -1.0f,-1.0f,-1.0f, // -Y side
135 -1.0f, 1.0f,-1.0f, // +Y side
142 1.0f, 1.0f,-1.0f, // +X side
149 -1.0f, 1.0f, 1.0f, // +Z side
157 static const float g_uv_buffer_data[] = {
158 0.0f, 1.0f, // -X side
165 1.0f, 1.0f, // -Z side
172 1.0f, 0.0f, // -Y side
179 1.0f, 0.0f, // +Y side
186 1.0f, 0.0f, // +X side
193 0.0f, 0.0f, // +Z side
204 vk::CommandBuffer cmd;
205 vk::CommandBuffer graphics_to_present_cmd;
207 vk::Buffer uniform_buffer;
208 vk::DeviceMemory uniform_memory;
209 vk::Framebuffer framebuffer;
210 vk::DescriptorSet descriptor_set;
211 } SwapchainImageResources;
215 void build_image_ownership_cmd(uint32_t const &);
216 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
218 void create_device();
219 void destroy_texture_image(texture_object *);
221 void draw_build_cmd(vk::CommandBuffer);
222 void flush_init_cmd();
223 void init(int, char **);
224 void init_connection();
226 void init_vk_swapchain();
228 void prepare_buffers();
229 void prepare_cube_data_buffers();
230 void prepare_depth();
231 void prepare_descriptor_layout();
232 void prepare_descriptor_pool();
233 void prepare_descriptor_set();
234 void prepare_framebuffers();
235 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
236 vk::ShaderModule prepare_vs();
237 vk::ShaderModule prepare_fs();
238 void prepare_pipeline();
239 void prepare_render_pass();
240 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
241 void prepare_textures();
244 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
245 vk::PipelineStageFlags, vk::PipelineStageFlags);
246 void update_data_buffer();
247 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
248 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
250 #if defined(VK_USE_PLATFORM_WIN32_KHR)
252 void create_window();
253 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
254 void create_xlib_window();
255 void handle_xlib_event(const XEvent *);
257 #elif defined(VK_USE_PLATFORM_XCB_KHR)
258 void handle_xcb_event(const xcb_generic_event_t *);
260 void create_xcb_window();
261 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
263 void create_window();
264 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
266 #elif defined(VK_USE_PLATFORM_MIR_KHR)
267 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
268 vk::Result create_display_surface();
272 #if defined(VK_USE_PLATFORM_WIN32_KHR)
273 HINSTANCE connection; // hInstance - Windows Instance
274 HWND window; // hWnd - window handle
275 POINT minsize; // minimum window size
276 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
277 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
279 Atom xlib_wm_delete_window;
281 #elif defined(VK_USE_PLATFORM_XCB_KHR)
282 xcb_window_t xcb_window;
283 xcb_screen_t *screen;
284 xcb_connection_t *connection;
285 xcb_intern_atom_reply_t *atom_wm_delete_window;
286 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
288 wl_registry *registry;
289 wl_compositor *compositor;
292 wl_shell_surface *shell_surface;
295 wl_keyboard *keyboard;
296 #elif defined(VK_USE_PLATFORM_MIR_KHR)
297 #elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
301 vk::SurfaceKHR surface;
303 bool use_staging_buffer;
305 bool separate_present_queue;
308 vk::PhysicalDevice gpu;
310 vk::Queue graphics_queue;
311 vk::Queue present_queue;
312 uint32_t graphics_queue_family_index;
313 uint32_t present_queue_family_index;
314 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
315 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
316 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
317 vk::PhysicalDeviceProperties gpu_props;
318 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
319 vk::PhysicalDeviceMemoryProperties memory_properties;
321 uint32_t enabled_extension_count;
322 uint32_t enabled_layer_count;
323 char const *extension_names[64];
324 char const *enabled_layers[64];
329 vk::ColorSpaceKHR color_space;
331 uint32_t swapchainImageCount;
332 vk::SwapchainKHR swapchain;
333 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
334 vk::PresentModeKHR presentMode;
335 vk::Fence fences[FRAME_LAG];
336 uint32_t frame_index;
338 vk::CommandPool cmd_pool;
339 vk::CommandPool present_cmd_pool;
344 vk::MemoryAllocateInfo mem_alloc;
345 vk::DeviceMemory mem;
349 static int32_t const texture_count = 1;
350 texture_object textures[texture_count];
351 texture_object staging_texture;
355 vk::MemoryAllocateInfo mem_alloc;
356 vk::DeviceMemory mem;
357 vk::DescriptorBufferInfo buffer_info;
360 vk::CommandBuffer cmd; // Buffer for initialization commands
361 vk::PipelineLayout pipeline_layout;
362 vk::DescriptorSetLayout desc_layout;
363 vk::PipelineCache pipelineCache;
364 vk::RenderPass render_pass;
365 vk::Pipeline pipeline;
367 mat4x4 projection_matrix;
372 float spin_increment;
375 vk::ShaderModule vert_shader_module;
376 vk::ShaderModule frag_shader_module;
378 vk::DescriptorPool desc_pool;
379 vk::DescriptorSet desc_set;
381 std::unique_ptr<vk::Framebuffer[]> framebuffers;
388 bool suppress_popups;
390 uint32_t current_buffer;
391 uint32_t queue_family_count;
395 // MS-Windows event handling function:
396 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
399 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
400 static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
401 wl_shell_surface_pong(shell_surface, serial);
404 static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
406 static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
408 static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
410 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
413 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
415 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
417 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
419 Demo *demo = (Demo *)data;
420 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
421 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
425 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
427 static const struct wl_pointer_listener pointer_listener = {
428 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
431 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
433 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
434 struct wl_array *keys) {}
436 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
438 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
440 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
441 Demo *demo = (Demo *)data;
443 case KEY_ESC: // Escape
446 case KEY_LEFT: // left arrow key
447 demo->spin_angle -= demo->spin_increment;
449 case KEY_RIGHT: // right arrow key
450 demo->spin_angle += demo->spin_increment;
452 case KEY_SPACE: // space bar
453 demo->pause = !demo->pause;
458 static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
459 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
461 static const struct wl_keyboard_listener keyboard_listener = {
462 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
465 static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
466 // Subscribe to pointer events
467 Demo *demo = (Demo *)data;
468 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
469 demo->pointer = wl_seat_get_pointer(seat);
470 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
471 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
472 wl_pointer_destroy(demo->pointer);
473 demo->pointer = NULL;
475 // Subscribe to keyboard events
476 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
477 demo->keyboard = wl_seat_get_keyboard(seat);
478 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
479 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
480 wl_keyboard_destroy(demo->keyboard);
481 demo->keyboard = NULL;
485 static const wl_seat_listener seat_listener = {
486 seat_handle_capabilities,
489 static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
490 Demo *demo = (Demo *)data;
491 // pickup wayland objects when they appear
492 if (strcmp(interface, "wl_compositor") == 0) {
493 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
494 } else if (strcmp(interface, "wl_shell") == 0) {
495 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
496 } else if (strcmp(interface, "wl_seat") == 0) {
497 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
498 wl_seat_add_listener(demo->seat, &seat_listener, demo);
502 static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
504 static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
505 #elif defined(VK_USE_PLATFORM_MIR_KHR)
510 #if defined(VK_USE_PLATFORM_WIN32_KHR)
513 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
516 #if defined(VK_USE_PLATFORM_XLIB_KHR)
518 xlib_wm_delete_window{0},
520 #elif defined(VK_USE_PLATFORM_XCB_KHR)
524 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
530 shell_surface{nullptr},
534 #elif defined(VK_USE_PLATFORM_MIR_KHR)
537 use_staging_buffer{false},
539 graphics_queue_family_index{0},
540 present_queue_family_index{0},
541 enabled_extension_count{0},
542 enabled_layer_count{0},
545 swapchainImageCount{0},
548 spin_increment{0.0f},
555 suppress_popups{false},
557 queue_family_count{0} {
558 #if defined(VK_USE_PLATFORM_WIN32_KHR)
559 memset(name, '\0', APP_NAME_STR_LEN);
561 memset(projection_matrix, 0, sizeof(projection_matrix));
562 memset(view_matrix, 0, sizeof(view_matrix));
563 memset(model_matrix, 0, sizeof(model_matrix));
566 void Demo::build_image_ownership_cmd(uint32_t const &i) {
567 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
568 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
569 VERIFY(result == vk::Result::eSuccess);
571 auto const image_ownership_barrier =
572 vk::ImageMemoryBarrier()
573 .setSrcAccessMask(vk::AccessFlags())
574 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
575 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
576 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
577 .setSrcQueueFamilyIndex(graphics_queue_family_index)
578 .setDstQueueFamilyIndex(present_queue_family_index)
579 .setImage(swapchain_image_resources[i].image)
580 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
582 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
583 vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput,
584 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
586 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
587 VERIFY(result == vk::Result::eSuccess);
590 vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
591 vk::LayerProperties *layers) {
592 for (uint32_t i = 0; i < check_count; i++) {
593 vk::Bool32 found = VK_FALSE;
594 for (uint32_t j = 0; j < layer_count; j++) {
595 if (!strcmp(check_names[i], layers[j].layerName)) {
601 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
608 void Demo::cleanup() {
612 // Wait for fences from present operations
613 for (uint32_t i = 0; i < FRAME_LAG; i++) {
614 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
615 device.destroyFence(fences[i], nullptr);
616 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
617 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
618 if (separate_present_queue) {
619 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
623 for (uint32_t i = 0; i < swapchainImageCount; i++) {
624 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
626 device.destroyDescriptorPool(desc_pool, nullptr);
628 device.destroyPipeline(pipeline, nullptr);
629 device.destroyPipelineCache(pipelineCache, nullptr);
630 device.destroyRenderPass(render_pass, nullptr);
631 device.destroyPipelineLayout(pipeline_layout, nullptr);
632 device.destroyDescriptorSetLayout(desc_layout, nullptr);
634 for (uint32_t i = 0; i < texture_count; i++) {
635 device.destroyImageView(textures[i].view, nullptr);
636 device.destroyImage(textures[i].image, nullptr);
637 device.freeMemory(textures[i].mem, nullptr);
638 device.destroySampler(textures[i].sampler, nullptr);
640 device.destroySwapchainKHR(swapchain, nullptr);
642 device.destroyImageView(depth.view, nullptr);
643 device.destroyImage(depth.image, nullptr);
644 device.freeMemory(depth.mem, nullptr);
646 for (uint32_t i = 0; i < swapchainImageCount; i++) {
647 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
648 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
649 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
650 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
653 device.destroyCommandPool(cmd_pool, nullptr);
655 if (separate_present_queue) {
656 device.destroyCommandPool(present_cmd_pool, nullptr);
659 device.destroy(nullptr);
660 inst.destroySurfaceKHR(surface, nullptr);
662 #if defined(VK_USE_PLATFORM_XLIB_KHR)
663 XDestroyWindow(display, xlib_window);
664 XCloseDisplay(display);
665 #elif defined(VK_USE_PLATFORM_XCB_KHR)
666 xcb_destroy_window(connection, xcb_window);
667 xcb_disconnect(connection);
668 free(atom_wm_delete_window);
669 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
670 wl_keyboard_destroy(keyboard);
671 wl_pointer_destroy(pointer);
672 wl_seat_destroy(seat);
673 wl_shell_surface_destroy(shell_surface);
674 wl_surface_destroy(window);
675 wl_shell_destroy(shell);
676 wl_compositor_destroy(compositor);
677 wl_registry_destroy(registry);
678 wl_display_disconnect(display);
679 #elif defined(VK_USE_PLATFORM_MIR_KHR)
682 inst.destroy(nullptr);
685 void Demo::create_device() {
686 float const priorities[1] = {0.0};
688 vk::DeviceQueueCreateInfo queues[2];
689 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
690 queues[0].setQueueCount(1);
691 queues[0].setPQueuePriorities(priorities);
693 auto deviceInfo = vk::DeviceCreateInfo()
694 .setQueueCreateInfoCount(1)
695 .setPQueueCreateInfos(queues)
696 .setEnabledLayerCount(0)
697 .setPpEnabledLayerNames(nullptr)
698 .setEnabledExtensionCount(enabled_extension_count)
699 .setPpEnabledExtensionNames((const char *const *)extension_names)
700 .setPEnabledFeatures(nullptr);
702 if (separate_present_queue) {
703 queues[1].setQueueFamilyIndex(present_queue_family_index);
704 queues[1].setQueueCount(1);
705 queues[1].setPQueuePriorities(priorities);
706 deviceInfo.setQueueCreateInfoCount(2);
709 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
710 VERIFY(result == vk::Result::eSuccess);
713 void Demo::destroy_texture_image(texture_object *tex_objs) {
714 // clean up staging resources
715 device.freeMemory(tex_objs->mem, nullptr);
716 device.destroyImage(tex_objs->image, nullptr);
720 // Ensure no more than FRAME_LAG renderings are outstanding
721 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
722 device.resetFences(1, &fences[frame_index]);
727 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), ¤t_buffer);
728 if (result == vk::Result::eErrorOutOfDateKHR) {
729 // demo->swapchain is out of date (e.g. the window was resized) and
730 // must be recreated:
732 } else if (result == vk::Result::eSuboptimalKHR) {
733 // swapchain is not as optimal as it could be, but the platform's
734 // presentation engine will still present the image correctly.
737 VERIFY(result == vk::Result::eSuccess);
739 } while (result != vk::Result::eSuccess);
741 update_data_buffer();
743 // Wait for the image acquired semaphore to be signaled to ensure
744 // that the image won't be rendered to until the presentation
745 // engine has fully released ownership to the application, and it is
746 // okay to render to the image.
747 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
748 auto const submit_info = vk::SubmitInfo()
749 .setPWaitDstStageMask(&pipe_stage_flags)
750 .setWaitSemaphoreCount(1)
751 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
752 .setCommandBufferCount(1)
753 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
754 .setSignalSemaphoreCount(1)
755 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
757 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
758 VERIFY(result == vk::Result::eSuccess);
760 if (separate_present_queue) {
761 // If we are using separate queues, change image ownership to the
762 // present queue before presenting, waiting for the draw complete
763 // semaphore and signalling the ownership released semaphore when
765 auto const present_submit_info = vk::SubmitInfo()
766 .setPWaitDstStageMask(&pipe_stage_flags)
767 .setWaitSemaphoreCount(1)
768 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
769 .setCommandBufferCount(1)
770 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
771 .setSignalSemaphoreCount(1)
772 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
774 result = present_queue.submit(1, &present_submit_info, vk::Fence());
775 VERIFY(result == vk::Result::eSuccess);
778 // If we are using separate queues we have to wait for image ownership,
779 // otherwise wait for draw complete
780 auto const presentInfo = vk::PresentInfoKHR()
781 .setWaitSemaphoreCount(1)
782 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
783 : &draw_complete_semaphores[frame_index])
784 .setSwapchainCount(1)
785 .setPSwapchains(&swapchain)
786 .setPImageIndices(¤t_buffer);
788 result = present_queue.presentKHR(&presentInfo);
790 frame_index %= FRAME_LAG;
791 if (result == vk::Result::eErrorOutOfDateKHR) {
792 // swapchain is out of date (e.g. the window was resized) and
793 // must be recreated:
795 } else if (result == vk::Result::eSuboptimalKHR) {
796 // swapchain is not as optimal as it could be, but the platform's
797 // presentation engine will still present the image correctly.
799 VERIFY(result == vk::Result::eSuccess);
803 void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
804 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
806 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
807 vk::ClearDepthStencilValue(1.0f, 0u)};
809 auto const passInfo = vk::RenderPassBeginInfo()
810 .setRenderPass(render_pass)
811 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
812 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
813 .setClearValueCount(2)
814 .setPClearValues(clearValues);
816 auto result = commandBuffer.begin(&commandInfo);
817 VERIFY(result == vk::Result::eSuccess);
819 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
820 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
821 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
822 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
824 auto const viewport =
825 vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f);
826 commandBuffer.setViewport(0, 1, &viewport);
828 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
829 commandBuffer.setScissor(0, 1, &scissor);
830 commandBuffer.draw(12 * 3, 1, 0, 0);
831 // Note that ending the renderpass changes the image's layout from
832 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
833 commandBuffer.endRenderPass();
835 if (separate_present_queue) {
836 // We have to transfer ownership from the graphics queue family to
838 // present queue family to be able to present. Note that we don't
840 // to transfer from present queue family back to graphics queue
842 // the start of the next frame because we don't care about the
844 // contents at that point.
845 auto const image_ownership_barrier =
846 vk::ImageMemoryBarrier()
847 .setSrcAccessMask(vk::AccessFlags())
848 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
849 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
850 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
851 .setSrcQueueFamilyIndex(graphics_queue_family_index)
852 .setDstQueueFamilyIndex(present_queue_family_index)
853 .setImage(swapchain_image_resources[current_buffer].image)
854 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
856 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eBottomOfPipe,
857 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
860 result = commandBuffer.end();
861 VERIFY(result == vk::Result::eSuccess);
864 void Demo::flush_init_cmd() {
866 // This function could get called twice if the texture uses a staging
868 // In that case the second call should be ignored
873 auto result = cmd.end();
874 VERIFY(result == vk::Result::eSuccess);
876 auto const fenceInfo = vk::FenceCreateInfo();
878 result = device.createFence(&fenceInfo, nullptr, &fence);
879 VERIFY(result == vk::Result::eSuccess);
881 vk::CommandBuffer const commandBuffers[] = {cmd};
882 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
884 result = graphics_queue.submit(1, &submitInfo, fence);
885 VERIFY(result == vk::Result::eSuccess);
887 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
888 VERIFY(result == vk::Result::eSuccess);
890 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
891 device.destroyFence(fence, nullptr);
893 cmd = vk::CommandBuffer();
896 void Demo::init(int argc, char **argv) {
897 vec3 eye = {0.0f, 3.0f, 5.0f};
898 vec3 origin = {0, 0, 0};
899 vec3 up = {0.0f, 1.0f, 0.0};
901 presentMode = vk::PresentModeKHR::eFifo;
902 frameCount = UINT32_MAX;
905 for (int i = 1; i < argc; i++) {
906 if (strcmp(argv[i], "--use_staging") == 0) {
907 use_staging_buffer = true;
910 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
911 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
915 if (strcmp(argv[i], "--break") == 0) {
919 if (strcmp(argv[i], "--validate") == 0) {
923 if (strcmp(argv[i], "--xlib") == 0) {
924 fprintf(stderr, "--xlib is deprecated and no longer does anything");
927 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
928 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
932 if (strcmp(argv[i], "--suppress_popups") == 0) {
933 suppress_popups = true;
938 "Usage:\n %s [--use_staging] [--validate] [--break] [--c <framecount>] \n"
939 " [--suppress_popups] [--present_mode {0,1,2,3}]\n"
941 "Options for --present_mode:\n"
942 " %d: VK_PRESENT_MODE_IMMEDIATE_KHR\n"
943 " %d: VK_PRESENT_MODE_MAILBOX_KHR\n"
944 " %d: VK_PRESENT_MODE_FIFO_KHR (default)\n"
945 " %d: VK_PRESENT_MODE_FIFO_RELAXED_KHR\n",
946 APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
947 VK_PRESENT_MODE_FIFO_RELAXED_KHR);
962 spin_increment = 0.2f;
965 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
966 mat4x4_look_at(view_matrix, eye, origin, up);
967 mat4x4_identity(model_matrix);
969 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
972 void Demo::init_connection() {
973 #if defined(VK_USE_PLATFORM_XCB_KHR)
974 const xcb_setup_t *setup;
975 xcb_screen_iterator_t iter;
978 const char *display_envar = getenv("DISPLAY");
979 if (display_envar == nullptr || display_envar[0] == '\0') {
980 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
985 connection = xcb_connect(nullptr, &scr);
986 if (xcb_connection_has_error(connection) > 0) {
988 "Cannot find a compatible Vulkan installable client driver "
989 "(ICD).\nExiting ...\n");
994 setup = xcb_get_setup(connection);
995 iter = xcb_setup_roots_iterator(setup);
996 while (scr-- > 0) xcb_screen_next(&iter);
999 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1000 display = wl_display_connect(nullptr);
1002 if (display == nullptr) {
1003 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1008 registry = wl_display_get_registry(display);
1009 wl_registry_add_listener(registry, ®istry_listener, this);
1010 wl_display_dispatch(display);
1011 #elif defined(VK_USE_PLATFORM_MIR_KHR)
1015 void Demo::init_vk() {
1016 uint32_t instance_extension_count = 0;
1017 uint32_t instance_layer_count = 0;
1018 uint32_t validation_layer_count = 0;
1019 char const *const *instance_validation_layers = nullptr;
1020 enabled_extension_count = 0;
1021 enabled_layer_count = 0;
1023 char const *const instance_validation_layers_alt1[] = {"VK_LAYER_LUNARG_standard_validation"};
1025 char const *const instance_validation_layers_alt2[] = {"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation",
1026 "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation",
1027 "VK_LAYER_GOOGLE_unique_objects"};
1029 // Look for validation layers
1030 vk::Bool32 validation_found = VK_FALSE;
1032 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, nullptr);
1033 VERIFY(result == vk::Result::eSuccess);
1035 instance_validation_layers = instance_validation_layers_alt1;
1036 if (instance_layer_count > 0) {
1037 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1038 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
1039 VERIFY(result == vk::Result::eSuccess);
1041 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers,
1042 instance_layer_count, instance_layers.get());
1043 if (validation_found) {
1044 enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
1045 enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation";
1046 validation_layer_count = 1;
1048 // use alternative set of validation layers
1049 instance_validation_layers = instance_validation_layers_alt2;
1050 enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
1051 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers,
1052 instance_layer_count, instance_layers.get());
1053 validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
1054 for (uint32_t i = 0; i < validation_layer_count; i++) {
1055 enabled_layers[i] = instance_validation_layers[i];
1060 if (!validation_found) {
1062 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1063 "Please look at the Getting Started guide for additional information.\n",
1064 "vkCreateInstance Failure");
1068 /* Look for instance extensions */
1069 vk::Bool32 surfaceExtFound = VK_FALSE;
1070 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1071 memset(extension_names, 0, sizeof(extension_names));
1073 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
1074 VERIFY(result == vk::Result::eSuccess);
1076 if (instance_extension_count > 0) {
1077 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1078 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1079 VERIFY(result == vk::Result::eSuccess);
1081 for (uint32_t i = 0; i < instance_extension_count; i++) {
1082 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1083 surfaceExtFound = 1;
1084 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1086 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1087 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1088 platformSurfaceExtFound = 1;
1089 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1091 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1092 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1093 platformSurfaceExtFound = 1;
1094 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1096 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1097 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1098 platformSurfaceExtFound = 1;
1099 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1101 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1102 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1103 platformSurfaceExtFound = 1;
1104 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1106 #elif defined(VK_USE_PLATFORM_MIR_KHR)
1107 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1108 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1109 platformSurfaceExtFound = 1;
1110 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1112 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1113 if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1114 platformSurfaceExtFound = 1;
1115 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1117 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1118 if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1119 platformSurfaceExtFound = 1;
1120 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1124 assert(enabled_extension_count < 64);
1128 if (!surfaceExtFound) {
1129 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1131 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1132 "Please look at the Getting Started guide for additional information.\n",
1133 "vkCreateInstance Failure");
1136 if (!platformSurfaceExtFound) {
1137 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1138 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1140 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1141 "Please look at the Getting Started guide for additional information.\n",
1142 "vkCreateInstance Failure");
1143 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1144 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1146 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1147 "Please look at the Getting Started guide for additional information.\n",
1148 "vkCreateInstance Failure");
1149 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1150 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1152 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1153 "Please look at the Getting Started guide for additional information.\n",
1154 "vkCreateInstance Failure");
1155 #elif defined(VK_USE_PLATFORM_MIR_KHR)
1156 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1157 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1159 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1160 "Please look at the Getting Started guide for additional information.\n",
1161 "vkCreateInstance Failure");
1162 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1163 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1165 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1166 "Please look at the Getting Started guide for additional information.\n",
1167 "vkCreateInstance Failure");
1168 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1169 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1170 " extension.\n\nDo you have a compatible "
1171 "Vulkan installable client driver (ICD) installed?\nPlease "
1172 "look at the Getting Started guide for additional "
1174 "vkCreateInstance Failure");
1175 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1176 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1177 " extension.\n\nDo you have a compatible "
1178 "Vulkan installable client driver (ICD) installed?\nPlease "
1179 "look at the Getting Started guide for additional "
1181 "vkCreateInstance Failure");
1184 auto const app = vk::ApplicationInfo()
1185 .setPApplicationName(APP_SHORT_NAME)
1186 .setApplicationVersion(0)
1187 .setPEngineName(APP_SHORT_NAME)
1188 .setEngineVersion(0)
1189 .setApiVersion(VK_API_VERSION_1_0);
1190 auto const inst_info = vk::InstanceCreateInfo()
1191 .setPApplicationInfo(&app)
1192 .setEnabledLayerCount(enabled_layer_count)
1193 .setPpEnabledLayerNames(instance_validation_layers)
1194 .setEnabledExtensionCount(enabled_extension_count)
1195 .setPpEnabledExtensionNames(extension_names);
1197 result = vk::createInstance(&inst_info, nullptr, &inst);
1198 if (result == vk::Result::eErrorIncompatibleDriver) {
1200 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1201 "Please look at the Getting Started guide for additional information.\n",
1202 "vkCreateInstance Failure");
1203 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1205 "Cannot find a specified extension library.\n"
1206 "Make sure your layers path is set appropriately.\n",
1207 "vkCreateInstance Failure");
1208 } else if (result != vk::Result::eSuccess) {
1210 "vkCreateInstance failed.\n\n"
1211 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1212 "Please look at the Getting Started guide for additional information.\n",
1213 "vkCreateInstance Failure");
1216 /* Make initial call to query gpu_count, then second call for gpu info*/
1218 result = inst.enumeratePhysicalDevices(&gpu_count, nullptr);
1219 VERIFY(result == vk::Result::eSuccess);
1221 if (gpu_count > 0) {
1222 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1223 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1224 VERIFY(result == vk::Result::eSuccess);
1225 /* For cube demo we just grab the first physical device */
1226 gpu = physical_devices[0];
1229 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1230 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1231 "Please look at the Getting Started guide for additional information.\n",
1232 "vkEnumeratePhysicalDevices Failure");
1235 /* Look for device extensions */
1236 uint32_t device_extension_count = 0;
1237 vk::Bool32 swapchainExtFound = VK_FALSE;
1238 enabled_extension_count = 0;
1239 memset(extension_names, 0, sizeof(extension_names));
1241 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, nullptr);
1242 VERIFY(result == vk::Result::eSuccess);
1244 if (device_extension_count > 0) {
1245 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1246 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
1247 VERIFY(result == vk::Result::eSuccess);
1249 for (uint32_t i = 0; i < device_extension_count; i++) {
1250 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1251 swapchainExtFound = 1;
1252 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
1254 assert(enabled_extension_count < 64);
1258 if (!swapchainExtFound) {
1259 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1261 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1262 "Please look at the Getting Started guide for additional information.\n",
1263 "vkCreateInstance Failure");
1266 gpu.getProperties(&gpu_props);
1268 /* Call with nullptr data to get count */
1269 gpu.getQueueFamilyProperties(&queue_family_count, nullptr);
1270 assert(queue_family_count >= 1);
1272 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1273 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
1275 // Query fine-grained feature support for this device.
1276 // If app has specific feature requirements it should check supported
1277 // features based on this query
1278 vk::PhysicalDeviceFeatures physDevFeatures;
1279 gpu.getFeatures(&physDevFeatures);
1282 void Demo::init_vk_swapchain() {
1283 // Create a WSI surface for the window:
1284 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1286 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1288 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1289 VERIFY(result == vk::Result::eSuccess);
1291 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1293 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1295 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1296 VERIFY(result == vk::Result::eSuccess);
1298 #elif defined(VK_USE_PLATFORM_MIR_KHR)
1299 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1301 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1303 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1304 VERIFY(result == vk::Result::eSuccess);
1306 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1308 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1310 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1311 VERIFY(result == vk::Result::eSuccess);
1313 #elif defined(VK_USE_PLATFORM_IOS_MVK)
1315 auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1317 auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1318 VERIFY(result == vk::Result::eSuccess);
1320 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
1322 auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1324 auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1325 VERIFY(result == vk::Result::eSuccess);
1327 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1329 auto result = create_display_surface();
1330 VERIFY(result == vk::Result::eSuccess);
1333 // Iterate over each queue to learn whether it supports presenting:
1334 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1335 for (uint32_t i = 0; i < queue_family_count; i++) {
1336 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1339 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1340 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1341 for (uint32_t i = 0; i < queue_family_count; i++) {
1342 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1343 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1344 graphicsQueueFamilyIndex = i;
1347 if (supportsPresent[i] == VK_TRUE) {
1348 graphicsQueueFamilyIndex = i;
1349 presentQueueFamilyIndex = i;
1355 if (presentQueueFamilyIndex == UINT32_MAX) {
1356 // If didn't find a queue that supports both graphics and present,
1358 // find a separate present queue.
1359 for (uint32_t i = 0; i < queue_family_count; ++i) {
1360 if (supportsPresent[i] == VK_TRUE) {
1361 presentQueueFamilyIndex = i;
1367 // Generate error if could not find both a graphics and a present queue
1368 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1369 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1372 graphics_queue_family_index = graphicsQueueFamilyIndex;
1373 present_queue_family_index = presentQueueFamilyIndex;
1374 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1378 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1379 if (!separate_present_queue) {
1380 present_queue = graphics_queue;
1382 device.getQueue(present_queue_family_index, 0, &present_queue);
1385 // Get the list of VkFormat's that are supported:
1386 uint32_t formatCount;
1387 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, nullptr);
1388 VERIFY(result == vk::Result::eSuccess);
1390 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1391 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1392 VERIFY(result == vk::Result::eSuccess);
1394 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1395 // the surface has no preferred format. Otherwise, at least one
1396 // supported format will be returned.
1397 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1398 format = vk::Format::eB8G8R8A8Unorm;
1400 assert(formatCount >= 1);
1401 format = surfFormats[0].format;
1403 color_space = surfFormats[0].colorSpace;
1408 // Create semaphores to synchronize acquiring presentable buffers before
1409 // rendering and waiting for drawing to be complete before presenting
1410 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1412 // Create fences that we can use to throttle if we get too far
1413 // ahead of the image presents
1414 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1415 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1416 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1417 VERIFY(result == vk::Result::eSuccess);
1419 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1420 VERIFY(result == vk::Result::eSuccess);
1422 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1423 VERIFY(result == vk::Result::eSuccess);
1425 if (separate_present_queue) {
1426 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1427 VERIFY(result == vk::Result::eSuccess);
1432 // Get Memory information and properties
1433 gpu.getMemoryProperties(&memory_properties);
1436 void Demo::prepare() {
1437 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1438 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1439 VERIFY(result == vk::Result::eSuccess);
1441 auto const cmd = vk::CommandBufferAllocateInfo()
1442 .setCommandPool(cmd_pool)
1443 .setLevel(vk::CommandBufferLevel::ePrimary)
1444 .setCommandBufferCount(1);
1446 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1447 VERIFY(result == vk::Result::eSuccess);
1449 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1451 result = this->cmd.begin(&cmd_buf_info);
1452 VERIFY(result == vk::Result::eSuccess);
1457 prepare_cube_data_buffers();
1459 prepare_descriptor_layout();
1460 prepare_render_pass();
1463 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1464 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1465 VERIFY(result == vk::Result::eSuccess);
1468 if (separate_present_queue) {
1469 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1471 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1472 VERIFY(result == vk::Result::eSuccess);
1474 auto const present_cmd = vk::CommandBufferAllocateInfo()
1475 .setCommandPool(present_cmd_pool)
1476 .setLevel(vk::CommandBufferLevel::ePrimary)
1477 .setCommandBufferCount(1);
1479 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1480 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1481 VERIFY(result == vk::Result::eSuccess);
1483 build_image_ownership_cmd(i);
1487 prepare_descriptor_pool();
1488 prepare_descriptor_set();
1490 prepare_framebuffers();
1492 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1494 draw_build_cmd(swapchain_image_resources[i].cmd);
1498 * Prepare functions above may generate pipeline commands
1499 * that need to be flushed before beginning the render loop.
1502 if (staging_texture.image) {
1503 destroy_texture_image(&staging_texture);
1510 void Demo::prepare_buffers() {
1511 vk::SwapchainKHR oldSwapchain = swapchain;
1513 // Check the surface capabilities and formats
1514 vk::SurfaceCapabilitiesKHR surfCapabilities;
1515 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1516 VERIFY(result == vk::Result::eSuccess);
1518 uint32_t presentModeCount;
1519 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, nullptr);
1520 VERIFY(result == vk::Result::eSuccess);
1522 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1523 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1524 VERIFY(result == vk::Result::eSuccess);
1526 vk::Extent2D swapchainExtent;
1527 // width and height are either both -1, or both not -1.
1528 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1529 // If the surface size is undefined, the size is set to
1530 // the size of the images requested.
1531 swapchainExtent.width = width;
1532 swapchainExtent.height = height;
1534 // If the surface size is defined, the swap chain size must match
1535 swapchainExtent = surfCapabilities.currentExtent;
1536 width = surfCapabilities.currentExtent.width;
1537 height = surfCapabilities.currentExtent.height;
1540 // The FIFO present mode is guaranteed by the spec to be supported
1541 // and to have no tearing. It's a great default present mode to use.
1542 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1544 // There are times when you may wish to use another present mode. The
1545 // following code shows how to select them, and the comments provide some
1546 // reasons you may wish to use them.
1548 // It should be noted that Vulkan 1.0 doesn't provide a method for
1549 // synchronizing rendering with the presentation engine's display. There
1550 // is a method provided for throttling rendering with the display, but
1551 // there are some presentation engines for which this method will not work.
1552 // If an application doesn't throttle its rendering, and if it renders much
1553 // faster than the refresh rate of the display, this can waste power on
1554 // mobile devices. That is because power is being spent rendering images
1555 // that may never be seen.
1557 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1559 // tearing, or have some way of synchronizing their rendering with the
1561 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1562 // generally render a new presentable image every refresh cycle, but are
1563 // occasionally early. In this case, the application wants the new
1565 // to be displayed instead of the previously-queued-for-presentation
1567 // that has not yet been displayed.
1568 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1569 // render a new presentable image every refresh cycle, but are
1571 // late. In this case (perhaps because of stuttering/latency concerns),
1572 // the application wants the late image to be immediately displayed,
1574 // though that may mean some tearing.
1576 if (presentMode != swapchainPresentMode) {
1577 for (size_t i = 0; i < presentModeCount; ++i) {
1578 if (presentModes[i] == presentMode) {
1579 swapchainPresentMode = presentMode;
1585 if (swapchainPresentMode != presentMode) {
1586 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1589 // Determine the number of VkImages to use in the swap chain.
1590 // Application desires to acquire 3 images at a time for triple
1592 uint32_t desiredNumOfSwapchainImages = 3;
1593 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1594 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1597 // If maxImageCount is 0, we can ask for as many images as we want,
1599 // we're limited to maxImageCount
1600 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1601 // Application must settle for fewer images than desired:
1602 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1605 vk::SurfaceTransformFlagBitsKHR preTransform;
1606 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1607 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1609 preTransform = surfCapabilities.currentTransform;
1612 // Find a supported composite alpha mode - one of these is guaranteed to be set
1613 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1614 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1615 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1616 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1617 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1618 vk::CompositeAlphaFlagBitsKHR::eInherit,
1620 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1621 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1622 compositeAlpha = compositeAlphaFlags[i];
1627 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1628 .setSurface(surface)
1629 .setMinImageCount(desiredNumOfSwapchainImages)
1630 .setImageFormat(format)
1631 .setImageColorSpace(color_space)
1632 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1633 .setImageArrayLayers(1)
1634 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1635 .setImageSharingMode(vk::SharingMode::eExclusive)
1636 .setQueueFamilyIndexCount(0)
1637 .setPQueueFamilyIndices(nullptr)
1638 .setPreTransform(preTransform)
1639 .setCompositeAlpha(compositeAlpha)
1640 .setPresentMode(swapchainPresentMode)
1642 .setOldSwapchain(oldSwapchain);
1644 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1645 VERIFY(result == vk::Result::eSuccess);
1647 // If we just re-created an existing swapchain, we should destroy the
1649 // swapchain at this point.
1650 // Note: destroying the swapchain also cleans up all its associated
1651 // presentable images once the platform is done with them.
1653 device.destroySwapchainKHR(oldSwapchain, nullptr);
1656 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, nullptr);
1657 VERIFY(result == vk::Result::eSuccess);
1659 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1660 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1661 VERIFY(result == vk::Result::eSuccess);
1663 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1665 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1666 auto color_image_view = vk::ImageViewCreateInfo()
1667 .setViewType(vk::ImageViewType::e2D)
1669 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1671 swapchain_image_resources[i].image = swapchainImages[i];
1673 color_image_view.image = swapchain_image_resources[i].image;
1675 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1676 VERIFY(result == vk::Result::eSuccess);
1680 void Demo::prepare_cube_data_buffers() {
1682 mat4x4_mul(VP, projection_matrix, view_matrix);
1685 mat4x4_mul(MVP, VP, model_matrix);
1687 vktexcube_vs_uniform data;
1688 memcpy(data.mvp, MVP, sizeof(MVP));
1689 // dumpMatrix("MVP", MVP)
1691 for (int32_t i = 0; i < 12 * 3; i++) {
1692 data.position[i][0] = g_vertex_buffer_data[i * 3];
1693 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1694 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1695 data.position[i][3] = 1.0f;
1696 data.attr[i][0] = g_uv_buffer_data[2 * i];
1697 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1698 data.attr[i][2] = 0;
1699 data.attr[i][3] = 0;
1702 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1704 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1705 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
1706 VERIFY(result == vk::Result::eSuccess);
1708 vk::MemoryRequirements mem_reqs;
1709 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1711 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
1713 bool const pass = memory_type_from_properties(
1714 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1715 &mem_alloc.memoryTypeIndex);
1718 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
1719 VERIFY(result == vk::Result::eSuccess);
1721 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1722 VERIFY(pData.result == vk::Result::eSuccess);
1724 memcpy(pData.value, &data, sizeof data);
1726 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1729 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
1730 VERIFY(result == vk::Result::eSuccess);
1734 void Demo::prepare_depth() {
1735 depth.format = vk::Format::eD16Unorm;
1737 auto const image = vk::ImageCreateInfo()
1738 .setImageType(vk::ImageType::e2D)
1739 .setFormat(depth.format)
1740 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1743 .setSamples(vk::SampleCountFlagBits::e1)
1744 .setTiling(vk::ImageTiling::eOptimal)
1745 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1746 .setSharingMode(vk::SharingMode::eExclusive)
1747 .setQueueFamilyIndexCount(0)
1748 .setPQueueFamilyIndices(nullptr)
1749 .setInitialLayout(vk::ImageLayout::eUndefined);
1751 auto result = device.createImage(&image, nullptr, &depth.image);
1752 VERIFY(result == vk::Result::eSuccess);
1754 vk::MemoryRequirements mem_reqs;
1755 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1757 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1758 depth.mem_alloc.setMemoryTypeIndex(0);
1760 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1761 &depth.mem_alloc.memoryTypeIndex);
1764 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1765 VERIFY(result == vk::Result::eSuccess);
1767 result = device.bindImageMemory(depth.image, depth.mem, 0);
1768 VERIFY(result == vk::Result::eSuccess);
1770 auto const view = vk::ImageViewCreateInfo()
1771 .setImage(depth.image)
1772 .setViewType(vk::ImageViewType::e2D)
1773 .setFormat(depth.format)
1774 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1775 result = device.createImageView(&view, nullptr, &depth.view);
1776 VERIFY(result == vk::Result::eSuccess);
1779 void Demo::prepare_descriptor_layout() {
1780 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1782 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1783 .setDescriptorCount(1)
1784 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1785 .setPImmutableSamplers(nullptr),
1786 vk::DescriptorSetLayoutBinding()
1788 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1789 .setDescriptorCount(texture_count)
1790 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1791 .setPImmutableSamplers(nullptr)};
1793 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1795 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1796 VERIFY(result == vk::Result::eSuccess);
1798 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1800 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1801 VERIFY(result == vk::Result::eSuccess);
1804 void Demo::prepare_descriptor_pool() {
1805 vk::DescriptorPoolSize const poolSizes[2] = {
1806 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1807 vk::DescriptorPoolSize()
1808 .setType(vk::DescriptorType::eCombinedImageSampler)
1809 .setDescriptorCount(swapchainImageCount * texture_count)};
1811 auto const descriptor_pool =
1812 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1814 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1815 VERIFY(result == vk::Result::eSuccess);
1818 void Demo::prepare_descriptor_set() {
1819 auto const alloc_info =
1820 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1822 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1824 vk::DescriptorImageInfo tex_descs[texture_count];
1825 for (uint32_t i = 0; i < texture_count; i++) {
1826 tex_descs[i].setSampler(textures[i].sampler);
1827 tex_descs[i].setImageView(textures[i].view);
1828 tex_descs[i].setImageLayout(vk::ImageLayout::eGeneral);
1831 vk::WriteDescriptorSet writes[2];
1833 writes[0].setDescriptorCount(1);
1834 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1835 writes[0].setPBufferInfo(&buffer_info);
1837 writes[1].setDstBinding(1);
1838 writes[1].setDescriptorCount(texture_count);
1839 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1840 writes[1].setPImageInfo(tex_descs);
1842 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1843 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
1844 VERIFY(result == vk::Result::eSuccess);
1846 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1847 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1848 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1849 device.updateDescriptorSets(2, writes, 0, nullptr);
1853 void Demo::prepare_framebuffers() {
1854 vk::ImageView attachments[2];
1855 attachments[1] = depth.view;
1857 auto const fb_info = vk::FramebufferCreateInfo()
1858 .setRenderPass(render_pass)
1859 .setAttachmentCount(2)
1860 .setPAttachments(attachments)
1861 .setWidth((uint32_t)width)
1862 .setHeight((uint32_t)height)
1865 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1866 attachments[0] = swapchain_image_resources[i].view;
1867 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
1868 VERIFY(result == vk::Result::eSuccess);
1872 vk::ShaderModule Demo::prepare_fs() {
1873 const uint32_t fragShaderCode[] = {
1874 #include "cube.frag.inc"
1877 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
1879 return frag_shader_module;
1882 void Demo::prepare_pipeline() {
1883 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1884 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1885 VERIFY(result == vk::Result::eSuccess);
1887 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1888 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1889 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1891 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1893 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1895 // TODO: Where are pViewports and pScissors set?
1896 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1898 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1899 .setDepthClampEnable(VK_FALSE)
1900 .setRasterizerDiscardEnable(VK_FALSE)
1901 .setPolygonMode(vk::PolygonMode::eFill)
1902 .setCullMode(vk::CullModeFlagBits::eBack)
1903 .setFrontFace(vk::FrontFace::eCounterClockwise)
1904 .setDepthBiasEnable(VK_FALSE)
1905 .setLineWidth(1.0f);
1907 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1909 auto const stencilOp =
1910 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1912 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1913 .setDepthTestEnable(VK_TRUE)
1914 .setDepthWriteEnable(VK_TRUE)
1915 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1916 .setDepthBoundsTestEnable(VK_FALSE)
1917 .setStencilTestEnable(VK_FALSE)
1918 .setFront(stencilOp)
1919 .setBack(stencilOp);
1921 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1922 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1923 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1925 auto const colorBlendInfo =
1926 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1928 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1930 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1932 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1934 .setPStages(shaderStageInfo)
1935 .setPVertexInputState(&vertexInputInfo)
1936 .setPInputAssemblyState(&inputAssemblyInfo)
1937 .setPViewportState(&viewportInfo)
1938 .setPRasterizationState(&rasterizationInfo)
1939 .setPMultisampleState(&multisampleInfo)
1940 .setPDepthStencilState(&depthStencilInfo)
1941 .setPColorBlendState(&colorBlendInfo)
1942 .setPDynamicState(&dynamicStateInfo)
1943 .setLayout(pipeline_layout)
1944 .setRenderPass(render_pass);
1946 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1947 VERIFY(result == vk::Result::eSuccess);
1949 device.destroyShaderModule(frag_shader_module, nullptr);
1950 device.destroyShaderModule(vert_shader_module, nullptr);
1953 void Demo::prepare_render_pass() {
1954 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1955 // because at the start of the renderpass, we don't care about their contents.
1956 // At the start of the subpass, the color attachment's layout will be transitioned
1957 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1958 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1959 // the renderpass, the color attachment's layout will be transitioned to
1960 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1961 // the renderpass, no barriers are necessary.
1962 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1964 .setSamples(vk::SampleCountFlagBits::e1)
1965 .setLoadOp(vk::AttachmentLoadOp::eClear)
1966 .setStoreOp(vk::AttachmentStoreOp::eStore)
1967 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1968 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1969 .setInitialLayout(vk::ImageLayout::eUndefined)
1970 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1971 vk::AttachmentDescription()
1972 .setFormat(depth.format)
1973 .setSamples(vk::SampleCountFlagBits::e1)
1974 .setLoadOp(vk::AttachmentLoadOp::eClear)
1975 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1976 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1977 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1978 .setInitialLayout(vk::ImageLayout::eUndefined)
1979 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1981 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1983 auto const depth_reference =
1984 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1986 auto const subpass = vk::SubpassDescription()
1987 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1988 .setInputAttachmentCount(0)
1989 .setPInputAttachments(nullptr)
1990 .setColorAttachmentCount(1)
1991 .setPColorAttachments(&color_reference)
1992 .setPResolveAttachments(nullptr)
1993 .setPDepthStencilAttachment(&depth_reference)
1994 .setPreserveAttachmentCount(0)
1995 .setPPreserveAttachments(nullptr);
1997 auto const rp_info = vk::RenderPassCreateInfo()
1998 .setAttachmentCount(2)
1999 .setPAttachments(attachments)
2001 .setPSubpasses(&subpass)
2002 .setDependencyCount(0)
2003 .setPDependencies(nullptr);
2005 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2006 VERIFY(result == vk::Result::eSuccess);
2009 vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2010 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2012 vk::ShaderModule module;
2013 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2014 VERIFY(result == vk::Result::eSuccess);
2019 void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2020 vk::MemoryPropertyFlags required_props) {
2023 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2024 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2027 tex_obj->tex_width = tex_width;
2028 tex_obj->tex_height = tex_height;
2030 auto const image_create_info = vk::ImageCreateInfo()
2031 .setImageType(vk::ImageType::e2D)
2032 .setFormat(vk::Format::eR8G8B8A8Unorm)
2033 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2036 .setSamples(vk::SampleCountFlagBits::e1)
2039 .setSharingMode(vk::SharingMode::eExclusive)
2040 .setQueueFamilyIndexCount(0)
2041 .setPQueueFamilyIndices(nullptr)
2042 .setInitialLayout(vk::ImageLayout::ePreinitialized);
2044 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2045 VERIFY(result == vk::Result::eSuccess);
2047 vk::MemoryRequirements mem_reqs;
2048 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
2050 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2051 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2053 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2054 VERIFY(pass == true);
2056 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2057 VERIFY(result == vk::Result::eSuccess);
2059 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2060 VERIFY(result == vk::Result::eSuccess);
2062 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2063 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2064 vk::SubresourceLayout layout;
2065 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
2067 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2068 VERIFY(data.result == vk::Result::eSuccess);
2070 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2071 fprintf(stderr, "Error loading texture: %s\n", filename);
2074 device.unmapMemory(tex_obj->mem);
2077 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2080 void Demo::prepare_textures() {
2081 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2082 vk::FormatProperties props;
2083 gpu.getFormatProperties(tex_format, &props);
2085 for (uint32_t i = 0; i < texture_count; i++) {
2086 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2087 /* Device can texture using linear textures */
2088 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2089 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2090 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2091 // shader to run until layout transition completes
2092 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2093 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2094 vk::PipelineStageFlagBits::eFragmentShader);
2095 staging_texture.image = vk::Image();
2096 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2097 /* Must use staging buffer to copy linear texture to optimized */
2099 prepare_texture_image(tex_files[i], &staging_texture, vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eTransferSrc,
2100 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2102 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2103 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2104 vk::MemoryPropertyFlagBits::eDeviceLocal);
2106 set_image_layout(staging_texture.image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2107 vk::ImageLayout::eTransferSrcOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2108 vk::PipelineStageFlagBits::eTransfer);
2110 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2111 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2112 vk::PipelineStageFlagBits::eTransfer);
2114 auto const subresource = vk::ImageSubresourceLayers()
2115 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2117 .setBaseArrayLayer(0)
2120 auto const copy_region = vk::ImageCopy()
2121 .setSrcSubresource(subresource)
2122 .setSrcOffset({0, 0, 0})
2123 .setDstSubresource(subresource)
2124 .setDstOffset({0, 0, 0})
2125 .setExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
2127 cmd.copyImage(staging_texture.image, vk::ImageLayout::eTransferSrcOptimal, textures[i].image,
2128 vk::ImageLayout::eTransferDstOptimal, 1, ©_region);
2130 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2131 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2132 vk::PipelineStageFlagBits::eFragmentShader);
2134 assert(!"No support for R8G8B8A8_UNORM as texture image format");
2137 auto const samplerInfo = vk::SamplerCreateInfo()
2138 .setMagFilter(vk::Filter::eNearest)
2139 .setMinFilter(vk::Filter::eNearest)
2140 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2141 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2142 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2143 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2144 .setMipLodBias(0.0f)
2145 .setAnisotropyEnable(VK_FALSE)
2146 .setMaxAnisotropy(1)
2147 .setCompareEnable(VK_FALSE)
2148 .setCompareOp(vk::CompareOp::eNever)
2151 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2152 .setUnnormalizedCoordinates(VK_FALSE);
2154 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2155 VERIFY(result == vk::Result::eSuccess);
2157 auto const viewInfo = vk::ImageViewCreateInfo()
2158 .setImage(textures[i].image)
2159 .setViewType(vk::ImageViewType::e2D)
2160 .setFormat(tex_format)
2161 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2163 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2164 VERIFY(result == vk::Result::eSuccess);
2168 vk::ShaderModule Demo::prepare_vs() {
2169 const uint32_t vertShaderCode[] = {
2170 #include "cube.vert.inc"
2173 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2175 return vert_shader_module;
2178 void Demo::resize() {
2181 // Don't react to resize until after first initialization.
2186 // In order to properly resize the window, we must re-create the
2188 // AND redo the command buffers, etc.
2190 // First, perform part of the cleanup() function:
2192 auto result = device.waitIdle();
2193 VERIFY(result == vk::Result::eSuccess);
2195 for (i = 0; i < swapchainImageCount; i++) {
2196 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2199 device.destroyDescriptorPool(desc_pool, nullptr);
2201 device.destroyPipeline(pipeline, nullptr);
2202 device.destroyPipelineCache(pipelineCache, nullptr);
2203 device.destroyRenderPass(render_pass, nullptr);
2204 device.destroyPipelineLayout(pipeline_layout, nullptr);
2205 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2207 for (i = 0; i < texture_count; i++) {
2208 device.destroyImageView(textures[i].view, nullptr);
2209 device.destroyImage(textures[i].image, nullptr);
2210 device.freeMemory(textures[i].mem, nullptr);
2211 device.destroySampler(textures[i].sampler, nullptr);
2214 device.destroyImageView(depth.view, nullptr);
2215 device.destroyImage(depth.image, nullptr);
2216 device.freeMemory(depth.mem, nullptr);
2218 for (i = 0; i < swapchainImageCount; i++) {
2219 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2220 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2221 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2222 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2225 device.destroyCommandPool(cmd_pool, nullptr);
2226 if (separate_present_queue) {
2227 device.destroyCommandPool(present_cmd_pool, nullptr);
2230 // Second, re-perform the prepare() function, which will re-create the
2235 void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2236 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2239 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2240 vk::AccessFlags flags;
2243 case vk::ImageLayout::eTransferDstOptimal:
2244 // Make sure anything that was copying from this image has
2246 flags = vk::AccessFlagBits::eTransferWrite;
2248 case vk::ImageLayout::eColorAttachmentOptimal:
2249 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2251 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2252 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2254 case vk::ImageLayout::eShaderReadOnlyOptimal:
2255 // Make sure any Copy or CPU writes to image are flushed
2256 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2258 case vk::ImageLayout::eTransferSrcOptimal:
2259 flags = vk::AccessFlagBits::eTransferRead;
2261 case vk::ImageLayout::ePresentSrcKHR:
2262 flags = vk::AccessFlagBits::eMemoryRead;
2271 auto const barrier = vk::ImageMemoryBarrier()
2272 .setSrcAccessMask(srcAccessMask)
2273 .setDstAccessMask(DstAccessMask(newLayout))
2274 .setOldLayout(oldLayout)
2275 .setNewLayout(newLayout)
2276 .setSrcQueueFamilyIndex(0)
2277 .setDstQueueFamilyIndex(0)
2279 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2281 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2284 void Demo::update_data_buffer() {
2286 mat4x4_mul(VP, projection_matrix, view_matrix);
2288 // Rotate around the Y axis
2290 mat4x4_dup(Model, model_matrix);
2291 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2294 mat4x4_mul(MVP, VP, model_matrix);
2296 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2297 VERIFY(data.result == vk::Result::eSuccess);
2299 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2301 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2304 /* Convert ppm image data from header file into RGBA texture image */
2305 #include "lunarg.ppm.h"
2306 bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height) {
2309 cPtr = (char *)lunarg_ppm;
2310 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
2313 while (strncmp(cPtr++, "\n", 1))
2315 sscanf(cPtr, "%u %u", width, height);
2316 if (rgba_data == NULL) {
2319 while (strncmp(cPtr++, "\n", 1))
2321 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
2324 while (strncmp(cPtr++, "\n", 1))
2326 for (int y = 0; y < *height; y++) {
2327 uint8_t *rowPtr = rgba_data;
2328 for (int x = 0; x < *width; x++) {
2329 memcpy(rowPtr, cPtr, 3);
2330 rowPtr[3] = 255; /* Alpha of 1 */
2334 rgba_data += layout->rowPitch;
2339 bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2340 // Search memtypes to find first index with those properties
2341 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2342 if ((typeBits & 1) == 1) {
2343 // Type is available, does it match user properties?
2344 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2352 // No memory types matched, return failure
2356 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2365 if (frameCount != INT_MAX && curFrame == frameCount) {
2366 PostQuitMessage(validation_error);
2370 void Demo::create_window() {
2371 WNDCLASSEX win_class;
2373 // Initialize the window class structure:
2374 win_class.cbSize = sizeof(WNDCLASSEX);
2375 win_class.style = CS_HREDRAW | CS_VREDRAW;
2376 win_class.lpfnWndProc = WndProc;
2377 win_class.cbClsExtra = 0;
2378 win_class.cbWndExtra = 0;
2379 win_class.hInstance = connection; // hInstance
2380 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2381 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2382 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2383 win_class.lpszMenuName = nullptr;
2384 win_class.lpszClassName = name;
2385 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2387 // Register window class:
2388 if (!RegisterClassEx(&win_class)) {
2389 // It didn't work, so try to give a useful error:
2390 printf("Unexpected error trying to start the application!\n");
2395 // Create window with the registered class:
2396 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2397 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2398 window = CreateWindowEx(0,
2401 WS_OVERLAPPEDWINDOW | // window style
2402 WS_VISIBLE | WS_SYSMENU,
2403 100, 100, // x/y coords
2404 wr.right - wr.left, // width
2405 wr.bottom - wr.top, // height
2406 nullptr, // handle to parent
2407 nullptr, // handle to menu
2408 connection, // hInstance
2409 nullptr); // no extra parameters
2412 // It didn't work, so try to give a useful error:
2413 printf("Cannot create a window in which to draw!\n");
2418 // Window client area size must be at least 1 pixel high, to prevent
2420 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2421 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2423 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2425 void Demo::create_xlib_window() {
2426 const char *display_envar = getenv("DISPLAY");
2427 if (display_envar == nullptr || display_envar[0] == '\0') {
2428 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2434 display = XOpenDisplay(nullptr);
2435 long visualMask = VisualScreenMask;
2436 int numberOfVisuals;
2437 XVisualInfo vInfoTemplate = {};
2438 vInfoTemplate.screen = DefaultScreen(display);
2439 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2441 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2443 XSetWindowAttributes windowAttributes = {};
2444 windowAttributes.colormap = colormap;
2445 windowAttributes.background_pixel = 0xFFFFFFFF;
2446 windowAttributes.border_pixel = 0;
2447 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2450 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2451 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2453 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2454 XMapWindow(display, xlib_window);
2456 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2459 void Demo::handle_xlib_event(const XEvent *event) {
2460 switch (event->type) {
2462 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2467 switch (event->xkey.keycode) {
2471 case 0x71: // left arrow key
2472 spin_angle -= spin_increment;
2474 case 0x72: // right arrow key
2475 spin_angle += spin_increment;
2477 case 0x41: // space bar
2482 case ConfigureNotify:
2483 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2484 width = event->xconfigure.width;
2485 height = event->xconfigure.height;
2494 void Demo::run_xlib() {
2499 XNextEvent(display, &event);
2500 handle_xlib_event(&event);
2502 while (XPending(display) > 0) {
2503 XNextEvent(display, &event);
2504 handle_xlib_event(&event);
2510 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2515 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2517 void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2518 uint8_t event_code = event->response_type & 0x7f;
2519 switch (event_code) {
2521 // TODO: Resize window
2523 case XCB_CLIENT_MESSAGE:
2524 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2528 case XCB_KEY_RELEASE: {
2529 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2531 switch (key->detail) {
2535 case 0x71: // left arrow key
2536 spin_angle -= spin_increment;
2538 case 0x72: // right arrow key
2539 spin_angle += spin_increment;
2541 case 0x41: // space bar
2546 case XCB_CONFIGURE_NOTIFY: {
2547 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2548 if ((width != cfg->width) || (height != cfg->height)) {
2550 height = cfg->height;
2559 void Demo::run_xcb() {
2560 xcb_flush(connection);
2563 xcb_generic_event_t *event;
2566 event = xcb_wait_for_event(connection);
2568 event = xcb_poll_for_event(connection);
2571 handle_xcb_event(event);
2573 event = xcb_poll_for_event(connection);
2578 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2584 void Demo::create_xcb_window() {
2585 uint32_t value_mask, value_list[32];
2587 xcb_window = xcb_generate_id(connection);
2589 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2590 value_list[0] = screen->black_pixel;
2591 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2593 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2594 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2596 /* Magic code that will send notification when window is destroyed */
2597 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2598 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2600 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2601 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2603 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2607 xcb_map_window(connection, xcb_window);
2609 // Force the x/y coordinates to 100,100 results are identical in
2612 const uint32_t coords[] = {100, 100};
2613 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2615 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2620 wl_display_dispatch(display);
2622 wl_display_dispatch_pending(display);
2623 update_data_buffer();
2626 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2633 void Demo::create_window() {
2634 window = wl_compositor_create_surface(compositor);
2636 printf("Can not create wayland_surface from compositor!\n");
2641 shell_surface = wl_shell_get_shell_surface(shell, window);
2642 if (!shell_surface) {
2643 printf("Can not get shell_surface from wayland_surface!\n");
2648 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2649 wl_shell_surface_set_toplevel(shell_surface);
2650 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
2652 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
2656 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2660 #elif defined(VK_USE_PLATFORM_MIR_KHR)
2661 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2663 vk::Result Demo::create_display_surface() {
2665 uint32_t display_count;
2666 uint32_t mode_count;
2667 uint32_t plane_count;
2668 vk::DisplayPropertiesKHR display_props;
2669 vk::DisplayKHR display;
2670 vk::DisplayModePropertiesKHR mode_props;
2671 vk::DisplayPlanePropertiesKHR *plane_props;
2672 vk::Bool32 found_plane = VK_FALSE;
2673 uint32_t plane_index;
2674 vk::Extent2D image_extent;
2676 // Get the first display
2677 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2678 VERIFY(result == vk::Result::eSuccess);
2680 if (display_count == 0) {
2681 printf("Cannot find any display!\n");
2687 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2688 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2690 display = display_props.display;
2692 // Get the first mode of the display
2693 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2694 VERIFY(result == vk::Result::eSuccess);
2696 if (mode_count == 0) {
2697 printf("Cannot find any mode for the display!\n");
2703 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2704 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2706 // Get the list of planes
2707 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2708 VERIFY(result == vk::Result::eSuccess);
2710 if (plane_count == 0) {
2711 printf("Cannot find any plane!\n");
2716 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2717 VERIFY(plane_props != nullptr);
2719 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2720 VERIFY(result == vk::Result::eSuccess);
2722 // Find a plane compatible with the display
2723 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2724 uint32_t supported_count;
2725 vk::DisplayKHR *supported_displays;
2727 // Disqualify planes that are bound to a different display
2728 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2732 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
2733 VERIFY(result == vk::Result::eSuccess);
2735 if (supported_count == 0) {
2739 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2740 VERIFY(supported_displays != nullptr);
2742 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
2743 VERIFY(result == vk::Result::eSuccess);
2745 for (uint32_t i = 0; i < supported_count; i++) {
2746 if (supported_displays[i] == display) {
2747 found_plane = VK_TRUE;
2752 free(supported_displays);
2760 printf("Cannot find a plane compatible with the display!\n");
2767 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2768 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2769 // Find a supported alpha mode
2770 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2771 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2772 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2773 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2774 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2775 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2777 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2778 if (planeCaps.supportedAlpha & alphaModes[i]) {
2779 alphaMode = alphaModes[i];
2784 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2785 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2787 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2788 .setDisplayMode(mode_props.displayMode)
2789 .setPlaneIndex(plane_index)
2790 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2791 .setGlobalAlpha(1.0f)
2792 .setAlphaMode(alphaMode)
2793 .setImageExtent(image_extent);
2795 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2798 void Demo::run_display() {
2803 if (frameCount != INT32_MAX && curFrame == frameCount) {
2811 // Include header required for parsing the command line options.
2812 #include <shellapi.h>
2816 // MS-Windows event handling function:
2817 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2820 PostQuitMessage(validation_error);
2825 case WM_GETMINMAXINFO: // set window's minimum size
2826 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2829 // Resize the application to the new window size, except when
2830 // it was minimized. Vulkan doesn't support images or swapchains
2831 // with width=0 and height=0.
2832 if (wParam != SIZE_MINIMIZED) {
2833 demo.width = lParam & 0xffff;
2834 demo.height = (lParam & 0xffff0000) >> 16;
2842 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2845 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
2846 // TODO: Gah.. refactor. This isn't 1989.
2848 bool done; // flag saying when app is complete
2852 // Ensure wParam is initialized.
2855 // Use the CommandLine functions to get the command line arguments.
2856 // Unfortunately, Microsoft outputs
2857 // this information as wide characters for Unicode, and we simply want the
2858 // Ascii version to be compatible
2859 // with the non-Windows side. So, we have to convert the information to
2860 // Ascii character strings.
2861 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
2862 if (nullptr == commandLineArgs) {
2867 argv = (char **)malloc(sizeof(char *) * argc);
2868 if (argv == nullptr) {
2871 for (int iii = 0; iii < argc; iii++) {
2872 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2873 size_t numConverted = 0;
2875 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
2876 if (argv[iii] != nullptr) {
2877 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
2885 demo.init(argc, argv);
2887 // Free up the items we had to allocate for the command line arguments.
2888 if (argc > 0 && argv != nullptr) {
2889 for (int iii = 0; iii < argc; iii++) {
2890 if (argv[iii] != nullptr) {
2897 demo.connection = hInstance;
2898 strncpy(demo.name, "cube", APP_NAME_STR_LEN);
2899 demo.create_window();
2900 demo.init_vk_swapchain();
2904 done = false; // initialize loop condition variable
2906 // main message loop
2908 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
2909 if (msg.message == WM_QUIT) // check for a quit message
2911 done = true; // if found, quit app
2913 /* Translate and dispatch to event queue*/
2914 TranslateMessage(&msg);
2915 DispatchMessage(&msg);
2917 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2922 return (int)msg.wParam;
2927 int main(int argc, char **argv) {
2930 demo.init(argc, argv);
2932 #if defined(VK_USE_PLATFORM_XCB_KHR)
2933 demo.create_xcb_window();
2934 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2935 demo.use_xlib = true;
2936 demo.create_xlib_window();
2937 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2938 demo.create_window();
2939 #elif defined(VK_USE_PLATFORM_MIR_KHR)
2942 demo.init_vk_swapchain();
2946 #if defined(VK_USE_PLATFORM_XCB_KHR)
2948 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2950 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2952 #elif defined(VK_USE_PLATFORM_MIR_KHR)
2953 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2959 return validation_error;
2962 #elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
2964 // Global function invoked from NS or UI views and controllers to create demo
2965 static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
2967 demo.init(argc, (char **)argv);
2969 demo.init_vk_swapchain();
2971 demo.spin_angle = 0.4f;
2975 #error "Platform not supported"