2 * Copyright (c) 2015-2019 The Khronos Group Inc.
3 * Copyright (c) 2015-2019 Valve Corporation
4 * Copyright (c) 2015-2019 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>
37 #define VULKAN_HPP_NO_SMART_HANDLE
38 #define VULKAN_HPP_NO_EXCEPTIONS
39 #define VULKAN_HPP_TYPESAFE_CONVERSION
40 #include <vulkan/vulkan.hpp>
41 #include <vulkan/vk_sdk_platform.h>
46 #define VERIFY(x) assert(x)
48 #define VERIFY(x) ((void)(x))
51 #define APP_SHORT_NAME "vkcube"
53 #define APP_NAME_STR_LEN 80
56 // Allow a maximum of two outstanding presentation operations.
59 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
62 #define ERR_EXIT(err_msg, err_class) \
64 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
68 #define ERR_EXIT(err_msg, err_class) \
70 printf("%s\n", err_msg); \
76 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 void *uniform_memory_ptr;
210 vk::Framebuffer framebuffer;
211 vk::DescriptorSet descriptor_set;
212 } SwapchainImageResources;
216 void build_image_ownership_cmd(uint32_t const &);
217 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
219 void create_device();
220 void destroy_texture(texture_object *);
222 void draw_build_cmd(vk::CommandBuffer);
223 void flush_init_cmd();
224 void init(int, char **);
225 void init_connection();
227 void init_vk_swapchain();
229 void prepare_buffers();
230 void prepare_cube_data_buffers();
231 void prepare_depth();
232 void prepare_descriptor_layout();
233 void prepare_descriptor_pool();
234 void prepare_descriptor_set();
235 void prepare_framebuffers();
236 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
237 vk::ShaderModule prepare_vs();
238 vk::ShaderModule prepare_fs();
239 void prepare_pipeline();
240 void prepare_render_pass();
241 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
242 void prepare_texture_buffer(const char *, texture_object *);
243 void prepare_textures();
246 void create_surface();
247 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
248 vk::PipelineStageFlags, vk::PipelineStageFlags);
249 void update_data_buffer();
250 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
251 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
253 #if defined(VK_USE_PLATFORM_WIN32_KHR)
255 void create_window();
256 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
257 void create_xlib_window();
258 void handle_xlib_event(const XEvent *);
260 #elif defined(VK_USE_PLATFORM_XCB_KHR)
261 void handle_xcb_event(const xcb_generic_event_t *);
263 void create_xcb_window();
264 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
266 void create_window();
267 #elif defined(VK_USE_PLATFORM_METAL_EXT)
269 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
270 vk::Result create_display_surface();
274 #if defined(VK_USE_PLATFORM_WIN32_KHR)
275 HINSTANCE connection; // hInstance - Windows Instance
276 HWND window; // hWnd - window handle
277 POINT minsize; // minimum window size
278 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
279 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
281 Atom xlib_wm_delete_window;
283 #elif defined(VK_USE_PLATFORM_XCB_KHR)
284 xcb_window_t xcb_window;
285 xcb_screen_t *screen;
286 xcb_connection_t *connection;
287 xcb_intern_atom_reply_t *atom_wm_delete_window;
288 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
290 wl_registry *registry;
291 wl_compositor *compositor;
294 wl_shell_surface *shell_surface;
297 wl_keyboard *keyboard;
298 #elif defined(VK_USE_PLATFORM_METAL_EXT)
302 vk::SurfaceKHR surface;
304 bool use_staging_buffer;
306 bool separate_present_queue;
309 vk::PhysicalDevice gpu;
311 vk::Queue graphics_queue;
312 vk::Queue present_queue;
313 uint32_t graphics_queue_family_index;
314 uint32_t present_queue_family_index;
315 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
316 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
317 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
318 vk::PhysicalDeviceProperties gpu_props;
319 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
320 vk::PhysicalDeviceMemoryProperties memory_properties;
322 uint32_t enabled_extension_count;
323 uint32_t enabled_layer_count;
324 char const *extension_names[64];
325 char const *enabled_layers[64];
330 vk::ColorSpaceKHR color_space;
332 uint32_t swapchainImageCount;
333 vk::SwapchainKHR swapchain;
334 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
335 vk::PresentModeKHR presentMode;
336 vk::Fence fences[FRAME_LAG];
337 uint32_t frame_index;
339 vk::CommandPool cmd_pool;
340 vk::CommandPool present_cmd_pool;
345 vk::MemoryAllocateInfo mem_alloc;
346 vk::DeviceMemory mem;
350 static int32_t const texture_count = 1;
351 texture_object textures[texture_count];
352 texture_object staging_texture;
356 vk::MemoryAllocateInfo mem_alloc;
357 vk::DeviceMemory mem;
358 vk::DescriptorBufferInfo buffer_info;
361 vk::CommandBuffer cmd; // Buffer for initialization commands
362 vk::PipelineLayout pipeline_layout;
363 vk::DescriptorSetLayout desc_layout;
364 vk::PipelineCache pipelineCache;
365 vk::RenderPass render_pass;
366 vk::Pipeline pipeline;
368 mat4x4 projection_matrix;
373 float spin_increment;
376 vk::ShaderModule vert_shader_module;
377 vk::ShaderModule frag_shader_module;
379 vk::DescriptorPool desc_pool;
380 vk::DescriptorSet desc_set;
382 std::unique_ptr<vk::Framebuffer[]> framebuffers;
389 bool suppress_popups;
391 uint32_t current_buffer;
392 uint32_t queue_family_count;
396 // MS-Windows event handling function:
397 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
400 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
401 static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
402 wl_shell_surface_pong(shell_surface, serial);
405 static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
407 static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
409 static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
411 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
414 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
416 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
418 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
420 Demo *demo = (Demo *)data;
421 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
422 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
426 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
428 static const struct wl_pointer_listener pointer_listener = {
429 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
432 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
434 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
435 struct wl_array *keys) {}
437 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
439 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
441 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
442 Demo *demo = (Demo *)data;
444 case KEY_ESC: // Escape
447 case KEY_LEFT: // left arrow key
448 demo->spin_angle -= demo->spin_increment;
450 case KEY_RIGHT: // right arrow key
451 demo->spin_angle += demo->spin_increment;
453 case KEY_SPACE: // space bar
454 demo->pause = !demo->pause;
459 static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
460 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
462 static const struct wl_keyboard_listener keyboard_listener = {
463 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
466 static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
467 // Subscribe to pointer events
468 Demo *demo = (Demo *)data;
469 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
470 demo->pointer = wl_seat_get_pointer(seat);
471 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
472 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
473 wl_pointer_destroy(demo->pointer);
474 demo->pointer = NULL;
476 // Subscribe to keyboard events
477 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
478 demo->keyboard = wl_seat_get_keyboard(seat);
479 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
480 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
481 wl_keyboard_destroy(demo->keyboard);
482 demo->keyboard = NULL;
486 static const wl_seat_listener seat_listener = {
487 seat_handle_capabilities,
490 static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
491 Demo *demo = (Demo *)data;
492 // pickup wayland objects when they appear
493 if (strcmp(interface, "wl_compositor") == 0) {
494 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
495 } else if (strcmp(interface, "wl_shell") == 0) {
496 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
497 } else if (strcmp(interface, "wl_seat") == 0) {
498 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
499 wl_seat_add_listener(demo->seat, &seat_listener, demo);
503 static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
505 static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
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},
536 use_staging_buffer{false},
538 graphics_queue_family_index{0},
539 present_queue_family_index{0},
540 enabled_extension_count{0},
541 enabled_layer_count{0},
544 swapchainImageCount{0},
545 presentMode{vk::PresentModeKHR::eFifo},
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::AccessFlags())
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::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
584 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.unmapMemory(swapchain_image_resources[i].uniform_memory);
651 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
654 device.destroyCommandPool(cmd_pool, nullptr);
656 if (separate_present_queue) {
657 device.destroyCommandPool(present_cmd_pool, nullptr);
660 device.destroy(nullptr);
661 inst.destroySurfaceKHR(surface, nullptr);
663 #if defined(VK_USE_PLATFORM_XLIB_KHR)
664 XDestroyWindow(display, xlib_window);
665 XCloseDisplay(display);
666 #elif defined(VK_USE_PLATFORM_XCB_KHR)
667 xcb_destroy_window(connection, xcb_window);
668 xcb_disconnect(connection);
669 free(atom_wm_delete_window);
670 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
671 wl_keyboard_destroy(keyboard);
672 wl_pointer_destroy(pointer);
673 wl_seat_destroy(seat);
674 wl_shell_surface_destroy(shell_surface);
675 wl_surface_destroy(window);
676 wl_shell_destroy(shell);
677 wl_compositor_destroy(compositor);
678 wl_registry_destroy(registry);
679 wl_display_disconnect(display);
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(texture_object *tex_objs) {
714 // clean up staging resources
715 device.freeMemory(tex_objs->mem, nullptr);
716 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
717 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
721 // Ensure no more than FRAME_LAG renderings are outstanding
722 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
723 device.resetFences(1, &fences[frame_index]);
728 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), ¤t_buffer);
729 if (result == vk::Result::eErrorOutOfDateKHR) {
730 // demo->swapchain is out of date (e.g. the window was resized) and
731 // must be recreated:
733 } else if (result == vk::Result::eSuboptimalKHR) {
734 // swapchain is not as optimal as it could be, but the platform's
735 // presentation engine will still present the image correctly.
737 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
738 inst.destroySurfaceKHR(surface, nullptr);
742 VERIFY(result == vk::Result::eSuccess);
744 } while (result != vk::Result::eSuccess);
746 update_data_buffer();
748 // Wait for the image acquired semaphore to be signaled to ensure
749 // that the image won't be rendered to until the presentation
750 // engine has fully released ownership to the application, and it is
751 // okay to render to the image.
752 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
753 auto const submit_info = vk::SubmitInfo()
754 .setPWaitDstStageMask(&pipe_stage_flags)
755 .setWaitSemaphoreCount(1)
756 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
757 .setCommandBufferCount(1)
758 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
759 .setSignalSemaphoreCount(1)
760 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
762 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
763 VERIFY(result == vk::Result::eSuccess);
765 if (separate_present_queue) {
766 // If we are using separate queues, change image ownership to the
767 // present queue before presenting, waiting for the draw complete
768 // semaphore and signalling the ownership released semaphore when
770 auto const present_submit_info = vk::SubmitInfo()
771 .setPWaitDstStageMask(&pipe_stage_flags)
772 .setWaitSemaphoreCount(1)
773 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
774 .setCommandBufferCount(1)
775 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
776 .setSignalSemaphoreCount(1)
777 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
779 result = present_queue.submit(1, &present_submit_info, vk::Fence());
780 VERIFY(result == vk::Result::eSuccess);
783 // If we are using separate queues we have to wait for image ownership,
784 // otherwise wait for draw complete
785 auto const presentInfo = vk::PresentInfoKHR()
786 .setWaitSemaphoreCount(1)
787 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
788 : &draw_complete_semaphores[frame_index])
789 .setSwapchainCount(1)
790 .setPSwapchains(&swapchain)
791 .setPImageIndices(¤t_buffer);
793 result = present_queue.presentKHR(&presentInfo);
795 frame_index %= FRAME_LAG;
796 if (result == vk::Result::eErrorOutOfDateKHR) {
797 // swapchain is out of date (e.g. the window was resized) and
798 // must be recreated:
800 } else if (result == vk::Result::eSuboptimalKHR) {
801 // swapchain is not as optimal as it could be, but the platform's
802 // presentation engine will still present the image correctly.
803 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
804 inst.destroySurfaceKHR(surface, nullptr);
808 VERIFY(result == vk::Result::eSuccess);
812 void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
813 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
815 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
816 vk::ClearDepthStencilValue(1.0f, 0u)};
818 auto const passInfo = vk::RenderPassBeginInfo()
819 .setRenderPass(render_pass)
820 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
821 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
822 .setClearValueCount(2)
823 .setPClearValues(clearValues);
825 auto result = commandBuffer.begin(&commandInfo);
826 VERIFY(result == vk::Result::eSuccess);
828 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
829 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
830 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
831 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
832 float viewport_dimension;
833 float viewport_x = 0.0f;
834 float viewport_y = 0.0f;
835 if (width < height) {
836 viewport_dimension = (float)width;
837 viewport_y = (height - width) / 2.0f;
839 viewport_dimension = (float)height;
840 viewport_x = (width - height) / 2.0f;
842 auto const viewport = vk::Viewport()
845 .setWidth((float)viewport_dimension)
846 .setHeight((float)viewport_dimension)
847 .setMinDepth((float)0.0f)
848 .setMaxDepth((float)1.0f);
849 commandBuffer.setViewport(0, 1, &viewport);
851 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
852 commandBuffer.setScissor(0, 1, &scissor);
853 commandBuffer.draw(12 * 3, 1, 0, 0);
854 // Note that ending the renderpass changes the image's layout from
855 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
856 commandBuffer.endRenderPass();
858 if (separate_present_queue) {
859 // We have to transfer ownership from the graphics queue family to
861 // present queue family to be able to present. Note that we don't
863 // to transfer from present queue family back to graphics queue
865 // the start of the next frame because we don't care about the
867 // contents at that point.
868 auto const image_ownership_barrier =
869 vk::ImageMemoryBarrier()
870 .setSrcAccessMask(vk::AccessFlags())
871 .setDstAccessMask(vk::AccessFlags())
872 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
873 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
874 .setSrcQueueFamilyIndex(graphics_queue_family_index)
875 .setDstQueueFamilyIndex(present_queue_family_index)
876 .setImage(swapchain_image_resources[current_buffer].image)
877 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
879 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
880 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
883 result = commandBuffer.end();
884 VERIFY(result == vk::Result::eSuccess);
887 void Demo::flush_init_cmd() {
889 // This function could get called twice if the texture uses a staging
891 // In that case the second call should be ignored
896 auto result = cmd.end();
897 VERIFY(result == vk::Result::eSuccess);
899 auto const fenceInfo = vk::FenceCreateInfo();
901 result = device.createFence(&fenceInfo, nullptr, &fence);
902 VERIFY(result == vk::Result::eSuccess);
904 vk::CommandBuffer const commandBuffers[] = {cmd};
905 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
907 result = graphics_queue.submit(1, &submitInfo, fence);
908 VERIFY(result == vk::Result::eSuccess);
910 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
911 VERIFY(result == vk::Result::eSuccess);
913 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
914 device.destroyFence(fence, nullptr);
916 cmd = vk::CommandBuffer();
919 void Demo::init(int argc, char **argv) {
920 vec3 eye = {0.0f, 3.0f, 5.0f};
921 vec3 origin = {0, 0, 0};
922 vec3 up = {0.0f, 1.0f, 0.0};
924 presentMode = vk::PresentModeKHR::eFifo;
925 frameCount = UINT32_MAX;
928 for (int i = 1; i < argc; i++) {
929 if (strcmp(argv[i], "--use_staging") == 0) {
930 use_staging_buffer = true;
933 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
934 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
938 if (strcmp(argv[i], "--break") == 0) {
942 if (strcmp(argv[i], "--validate") == 0) {
946 if (strcmp(argv[i], "--xlib") == 0) {
947 fprintf(stderr, "--xlib is deprecated and no longer does anything");
950 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
951 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
955 if (strcmp(argv[i], "--suppress_popups") == 0) {
956 suppress_popups = true;
960 std::stringstream usage;
961 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
962 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
963 << "\t[--present_mode <present mode enum>]\n"
964 << "\t<present_mode_enum>\n"
965 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
966 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
967 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
968 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
971 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
973 std::cerr << usage.str();
989 spin_increment = 0.2f;
992 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
993 mat4x4_look_at(view_matrix, eye, origin, up);
994 mat4x4_identity(model_matrix);
996 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
999 void Demo::init_connection() {
1000 #if defined(VK_USE_PLATFORM_XCB_KHR)
1001 const xcb_setup_t *setup;
1002 xcb_screen_iterator_t iter;
1005 const char *display_envar = getenv("DISPLAY");
1006 if (display_envar == nullptr || display_envar[0] == '\0') {
1007 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1012 connection = xcb_connect(nullptr, &scr);
1013 if (xcb_connection_has_error(connection) > 0) {
1015 "Cannot find a compatible Vulkan installable client driver "
1016 "(ICD).\nExiting ...\n");
1021 setup = xcb_get_setup(connection);
1022 iter = xcb_setup_roots_iterator(setup);
1023 while (scr-- > 0) xcb_screen_next(&iter);
1026 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1027 display = wl_display_connect(nullptr);
1029 if (display == nullptr) {
1030 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1035 registry = wl_display_get_registry(display);
1036 wl_registry_add_listener(registry, ®istry_listener, this);
1037 wl_display_dispatch(display);
1041 void Demo::init_vk() {
1042 uint32_t instance_extension_count = 0;
1043 uint32_t instance_layer_count = 0;
1044 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
1045 enabled_extension_count = 0;
1046 enabled_layer_count = 0;
1048 // Look for validation layers
1049 vk::Bool32 validation_found = VK_FALSE;
1051 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
1052 VERIFY(result == vk::Result::eSuccess);
1054 if (instance_layer_count > 0) {
1055 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1056 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
1057 VERIFY(result == vk::Result::eSuccess);
1059 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
1060 instance_layer_count, instance_layers.get());
1061 if (validation_found) {
1062 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1063 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
1067 if (!validation_found) {
1069 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1070 "Please look at the Getting Started guide for additional information.\n",
1071 "vkCreateInstance Failure");
1075 /* Look for instance extensions */
1076 vk::Bool32 surfaceExtFound = VK_FALSE;
1077 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1078 memset(extension_names, 0, sizeof(extension_names));
1080 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1081 static_cast<vk::ExtensionProperties *>(nullptr));
1082 VERIFY(result == vk::Result::eSuccess);
1084 if (instance_extension_count > 0) {
1085 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1086 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1087 VERIFY(result == vk::Result::eSuccess);
1089 for (uint32_t i = 0; i < instance_extension_count; i++) {
1090 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1091 surfaceExtFound = 1;
1092 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1094 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1095 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1096 platformSurfaceExtFound = 1;
1097 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1099 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1100 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1101 platformSurfaceExtFound = 1;
1102 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1104 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1105 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1106 platformSurfaceExtFound = 1;
1107 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1109 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1110 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1111 platformSurfaceExtFound = 1;
1112 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1114 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1115 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1116 platformSurfaceExtFound = 1;
1117 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1119 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1120 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1121 platformSurfaceExtFound = 1;
1122 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
1126 assert(enabled_extension_count < 64);
1130 if (!surfaceExtFound) {
1131 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1133 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1134 "Please look at the Getting Started guide for additional information.\n",
1135 "vkCreateInstance Failure");
1138 if (!platformSurfaceExtFound) {
1139 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1140 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1142 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1143 "Please look at the Getting Started guide for additional information.\n",
1144 "vkCreateInstance Failure");
1145 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1146 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1148 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1149 "Please look at the Getting Started guide for additional information.\n",
1150 "vkCreateInstance Failure");
1151 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1152 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1154 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1155 "Please look at the Getting Started guide for additional information.\n",
1156 "vkCreateInstance Failure");
1157 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1158 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1160 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1161 "Please look at the Getting Started guide for additional information.\n",
1162 "vkCreateInstance Failure");
1163 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1164 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1166 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1167 "Please look at the Getting Started guide for additional information.\n",
1168 "vkCreateInstance Failure");
1169 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1170 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
1171 " extension.\n\nDo you have a compatible "
1172 "Vulkan installable client driver (ICD) installed?\nPlease "
1173 "look at the Getting Started guide for additional "
1175 "vkCreateInstance Failure");
1178 auto const app = vk::ApplicationInfo()
1179 .setPApplicationName(APP_SHORT_NAME)
1180 .setApplicationVersion(0)
1181 .setPEngineName(APP_SHORT_NAME)
1182 .setEngineVersion(0)
1183 .setApiVersion(VK_API_VERSION_1_0);
1184 auto const inst_info = vk::InstanceCreateInfo()
1185 .setPApplicationInfo(&app)
1186 .setEnabledLayerCount(enabled_layer_count)
1187 .setPpEnabledLayerNames(instance_validation_layers)
1188 .setEnabledExtensionCount(enabled_extension_count)
1189 .setPpEnabledExtensionNames(extension_names);
1191 result = vk::createInstance(&inst_info, nullptr, &inst);
1192 if (result == vk::Result::eErrorIncompatibleDriver) {
1194 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1195 "Please look at the Getting Started guide for additional information.\n",
1196 "vkCreateInstance Failure");
1197 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1199 "Cannot find a specified extension library.\n"
1200 "Make sure your layers path is set appropriately.\n",
1201 "vkCreateInstance Failure");
1202 } else if (result != vk::Result::eSuccess) {
1204 "vkCreateInstance failed.\n\n"
1205 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1206 "Please look at the Getting Started guide for additional information.\n",
1207 "vkCreateInstance Failure");
1210 /* Make initial call to query gpu_count, then second call for gpu info*/
1212 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
1213 VERIFY(result == vk::Result::eSuccess);
1215 if (gpu_count > 0) {
1216 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1217 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1218 VERIFY(result == vk::Result::eSuccess);
1219 /* For cube demo we just grab the first physical device */
1220 gpu = physical_devices[0];
1223 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1224 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1225 "Please look at the Getting Started guide for additional information.\n",
1226 "vkEnumeratePhysicalDevices Failure");
1229 /* Look for device extensions */
1230 uint32_t device_extension_count = 0;
1231 vk::Bool32 swapchainExtFound = VK_FALSE;
1232 enabled_extension_count = 0;
1233 memset(extension_names, 0, sizeof(extension_names));
1236 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
1237 VERIFY(result == vk::Result::eSuccess);
1239 if (device_extension_count > 0) {
1240 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1241 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
1242 VERIFY(result == vk::Result::eSuccess);
1244 for (uint32_t i = 0; i < device_extension_count; i++) {
1245 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1246 swapchainExtFound = 1;
1247 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
1249 assert(enabled_extension_count < 64);
1253 if (!swapchainExtFound) {
1254 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1256 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1257 "Please look at the Getting Started guide for additional information.\n",
1258 "vkCreateInstance Failure");
1261 gpu.getProperties(&gpu_props);
1263 /* Call with nullptr data to get count */
1264 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
1265 assert(queue_family_count >= 1);
1267 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1268 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
1270 // Query fine-grained feature support for this device.
1271 // If app has specific feature requirements it should check supported
1272 // features based on this query
1273 vk::PhysicalDeviceFeatures physDevFeatures;
1274 gpu.getFeatures(&physDevFeatures);
1277 void Demo::create_surface() {
1278 // Create a WSI surface for the window:
1279 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1281 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1283 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1284 VERIFY(result == vk::Result::eSuccess);
1286 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1288 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1290 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1291 VERIFY(result == vk::Result::eSuccess);
1293 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1295 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1297 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1298 VERIFY(result == vk::Result::eSuccess);
1300 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1302 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1304 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1305 VERIFY(result == vk::Result::eSuccess);
1307 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1309 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
1311 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
1312 VERIFY(result == vk::Result::eSuccess);
1314 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1316 auto result = create_display_surface();
1317 VERIFY(result == vk::Result::eSuccess);
1322 void Demo::init_vk_swapchain() {
1324 // Iterate over each queue to learn whether it supports presenting:
1325 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1326 for (uint32_t i = 0; i < queue_family_count; i++) {
1327 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1330 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1331 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1332 for (uint32_t i = 0; i < queue_family_count; i++) {
1333 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1334 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1335 graphicsQueueFamilyIndex = i;
1338 if (supportsPresent[i] == VK_TRUE) {
1339 graphicsQueueFamilyIndex = i;
1340 presentQueueFamilyIndex = i;
1346 if (presentQueueFamilyIndex == UINT32_MAX) {
1347 // If didn't find a queue that supports both graphics and present,
1349 // find a separate present queue.
1350 for (uint32_t i = 0; i < queue_family_count; ++i) {
1351 if (supportsPresent[i] == VK_TRUE) {
1352 presentQueueFamilyIndex = i;
1358 // Generate error if could not find both a graphics and a present queue
1359 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1360 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1363 graphics_queue_family_index = graphicsQueueFamilyIndex;
1364 present_queue_family_index = presentQueueFamilyIndex;
1365 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1369 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1370 if (!separate_present_queue) {
1371 present_queue = graphics_queue;
1373 device.getQueue(present_queue_family_index, 0, &present_queue);
1376 // Get the list of VkFormat's that are supported:
1377 uint32_t formatCount;
1378 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
1379 VERIFY(result == vk::Result::eSuccess);
1381 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1382 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1383 VERIFY(result == vk::Result::eSuccess);
1385 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1386 // the surface has no preferred format. Otherwise, at least one
1387 // supported format will be returned.
1388 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1389 format = vk::Format::eB8G8R8A8Unorm;
1391 assert(formatCount >= 1);
1392 format = surfFormats[0].format;
1394 color_space = surfFormats[0].colorSpace;
1399 // Create semaphores to synchronize acquiring presentable buffers before
1400 // rendering and waiting for drawing to be complete before presenting
1401 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1403 // Create fences that we can use to throttle if we get too far
1404 // ahead of the image presents
1405 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1406 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1407 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1408 VERIFY(result == vk::Result::eSuccess);
1410 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1411 VERIFY(result == vk::Result::eSuccess);
1413 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1414 VERIFY(result == vk::Result::eSuccess);
1416 if (separate_present_queue) {
1417 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1418 VERIFY(result == vk::Result::eSuccess);
1423 // Get Memory information and properties
1424 gpu.getMemoryProperties(&memory_properties);
1427 void Demo::prepare() {
1428 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1429 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1430 VERIFY(result == vk::Result::eSuccess);
1432 auto const cmd = vk::CommandBufferAllocateInfo()
1433 .setCommandPool(cmd_pool)
1434 .setLevel(vk::CommandBufferLevel::ePrimary)
1435 .setCommandBufferCount(1);
1437 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1438 VERIFY(result == vk::Result::eSuccess);
1440 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1442 result = this->cmd.begin(&cmd_buf_info);
1443 VERIFY(result == vk::Result::eSuccess);
1448 prepare_cube_data_buffers();
1450 prepare_descriptor_layout();
1451 prepare_render_pass();
1454 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1455 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1456 VERIFY(result == vk::Result::eSuccess);
1459 if (separate_present_queue) {
1460 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1462 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1463 VERIFY(result == vk::Result::eSuccess);
1465 auto const present_cmd = vk::CommandBufferAllocateInfo()
1466 .setCommandPool(present_cmd_pool)
1467 .setLevel(vk::CommandBufferLevel::ePrimary)
1468 .setCommandBufferCount(1);
1470 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1471 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1472 VERIFY(result == vk::Result::eSuccess);
1474 build_image_ownership_cmd(i);
1478 prepare_descriptor_pool();
1479 prepare_descriptor_set();
1481 prepare_framebuffers();
1483 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1485 draw_build_cmd(swapchain_image_resources[i].cmd);
1489 * Prepare functions above may generate pipeline commands
1490 * that need to be flushed before beginning the render loop.
1493 if (staging_texture.buffer) {
1494 destroy_texture(&staging_texture);
1501 void Demo::prepare_buffers() {
1502 vk::SwapchainKHR oldSwapchain = swapchain;
1504 // Check the surface capabilities and formats
1505 vk::SurfaceCapabilitiesKHR surfCapabilities;
1506 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1507 VERIFY(result == vk::Result::eSuccess);
1509 uint32_t presentModeCount;
1510 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
1511 VERIFY(result == vk::Result::eSuccess);
1513 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1514 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1515 VERIFY(result == vk::Result::eSuccess);
1517 vk::Extent2D swapchainExtent;
1518 // width and height are either both -1, or both not -1.
1519 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1520 // If the surface size is undefined, the size is set to
1521 // the size of the images requested.
1522 swapchainExtent.width = width;
1523 swapchainExtent.height = height;
1525 // If the surface size is defined, the swap chain size must match
1526 swapchainExtent = surfCapabilities.currentExtent;
1527 width = surfCapabilities.currentExtent.width;
1528 height = surfCapabilities.currentExtent.height;
1531 // The FIFO present mode is guaranteed by the spec to be supported
1532 // and to have no tearing. It's a great default present mode to use.
1533 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1535 // There are times when you may wish to use another present mode. The
1536 // following code shows how to select them, and the comments provide some
1537 // reasons you may wish to use them.
1539 // It should be noted that Vulkan 1.0 doesn't provide a method for
1540 // synchronizing rendering with the presentation engine's display. There
1541 // is a method provided for throttling rendering with the display, but
1542 // there are some presentation engines for which this method will not work.
1543 // If an application doesn't throttle its rendering, and if it renders much
1544 // faster than the refresh rate of the display, this can waste power on
1545 // mobile devices. That is because power is being spent rendering images
1546 // that may never be seen.
1548 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1550 // tearing, or have some way of synchronizing their rendering with the
1552 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1553 // generally render a new presentable image every refresh cycle, but are
1554 // occasionally early. In this case, the application wants the new
1556 // to be displayed instead of the previously-queued-for-presentation
1558 // that has not yet been displayed.
1559 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1560 // render a new presentable image every refresh cycle, but are
1562 // late. In this case (perhaps because of stuttering/latency concerns),
1563 // the application wants the late image to be immediately displayed,
1565 // though that may mean some tearing.
1567 if (presentMode != swapchainPresentMode) {
1568 for (size_t i = 0; i < presentModeCount; ++i) {
1569 if (presentModes[i] == presentMode) {
1570 swapchainPresentMode = presentMode;
1576 if (swapchainPresentMode != presentMode) {
1577 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1580 // Determine the number of VkImages to use in the swap chain.
1581 // Application desires to acquire 3 images at a time for triple
1583 uint32_t desiredNumOfSwapchainImages = 3;
1584 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1585 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1588 // If maxImageCount is 0, we can ask for as many images as we want,
1590 // we're limited to maxImageCount
1591 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1592 // Application must settle for fewer images than desired:
1593 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1596 vk::SurfaceTransformFlagBitsKHR preTransform;
1597 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1598 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1600 preTransform = surfCapabilities.currentTransform;
1603 // Find a supported composite alpha mode - one of these is guaranteed to be set
1604 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1605 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1606 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1607 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1608 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1609 vk::CompositeAlphaFlagBitsKHR::eInherit,
1611 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1612 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1613 compositeAlpha = compositeAlphaFlags[i];
1618 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1619 .setSurface(surface)
1620 .setMinImageCount(desiredNumOfSwapchainImages)
1621 .setImageFormat(format)
1622 .setImageColorSpace(color_space)
1623 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1624 .setImageArrayLayers(1)
1625 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1626 .setImageSharingMode(vk::SharingMode::eExclusive)
1627 .setQueueFamilyIndexCount(0)
1628 .setPQueueFamilyIndices(nullptr)
1629 .setPreTransform(preTransform)
1630 .setCompositeAlpha(compositeAlpha)
1631 .setPresentMode(swapchainPresentMode)
1633 .setOldSwapchain(oldSwapchain);
1635 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1636 VERIFY(result == vk::Result::eSuccess);
1638 // If we just re-created an existing swapchain, we should destroy the
1640 // swapchain at this point.
1641 // Note: destroying the swapchain also cleans up all its associated
1642 // presentable images once the platform is done with them.
1644 device.destroySwapchainKHR(oldSwapchain, nullptr);
1647 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
1648 VERIFY(result == vk::Result::eSuccess);
1650 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1651 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1652 VERIFY(result == vk::Result::eSuccess);
1654 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1656 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1657 auto color_image_view = vk::ImageViewCreateInfo()
1658 .setViewType(vk::ImageViewType::e2D)
1660 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1662 swapchain_image_resources[i].image = swapchainImages[i];
1664 color_image_view.image = swapchain_image_resources[i].image;
1666 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1667 VERIFY(result == vk::Result::eSuccess);
1671 void Demo::prepare_cube_data_buffers() {
1673 mat4x4_mul(VP, projection_matrix, view_matrix);
1676 mat4x4_mul(MVP, VP, model_matrix);
1678 vktexcube_vs_uniform data;
1679 memcpy(data.mvp, MVP, sizeof(MVP));
1680 // dumpMatrix("MVP", MVP)
1682 for (int32_t i = 0; i < 12 * 3; i++) {
1683 data.position[i][0] = g_vertex_buffer_data[i * 3];
1684 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1685 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1686 data.position[i][3] = 1.0f;
1687 data.attr[i][0] = g_uv_buffer_data[2 * i];
1688 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1689 data.attr[i][2] = 0;
1690 data.attr[i][3] = 0;
1693 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1695 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1696 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
1697 VERIFY(result == vk::Result::eSuccess);
1699 vk::MemoryRequirements mem_reqs;
1700 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1702 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
1704 bool const pass = memory_type_from_properties(
1705 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1706 &mem_alloc.memoryTypeIndex);
1709 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
1710 VERIFY(result == vk::Result::eSuccess);
1712 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1713 &swapchain_image_resources[i].uniform_memory_ptr);
1714 VERIFY(result == vk::Result::eSuccess);
1716 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
1719 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
1720 VERIFY(result == vk::Result::eSuccess);
1724 void Demo::prepare_depth() {
1725 depth.format = vk::Format::eD16Unorm;
1727 auto const image = vk::ImageCreateInfo()
1728 .setImageType(vk::ImageType::e2D)
1729 .setFormat(depth.format)
1730 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1733 .setSamples(vk::SampleCountFlagBits::e1)
1734 .setTiling(vk::ImageTiling::eOptimal)
1735 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1736 .setSharingMode(vk::SharingMode::eExclusive)
1737 .setQueueFamilyIndexCount(0)
1738 .setPQueueFamilyIndices(nullptr)
1739 .setInitialLayout(vk::ImageLayout::eUndefined);
1741 auto result = device.createImage(&image, nullptr, &depth.image);
1742 VERIFY(result == vk::Result::eSuccess);
1744 vk::MemoryRequirements mem_reqs;
1745 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1747 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1748 depth.mem_alloc.setMemoryTypeIndex(0);
1750 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1751 &depth.mem_alloc.memoryTypeIndex);
1754 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1755 VERIFY(result == vk::Result::eSuccess);
1757 result = device.bindImageMemory(depth.image, depth.mem, 0);
1758 VERIFY(result == vk::Result::eSuccess);
1760 auto const view = vk::ImageViewCreateInfo()
1761 .setImage(depth.image)
1762 .setViewType(vk::ImageViewType::e2D)
1763 .setFormat(depth.format)
1764 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1765 result = device.createImageView(&view, nullptr, &depth.view);
1766 VERIFY(result == vk::Result::eSuccess);
1769 void Demo::prepare_descriptor_layout() {
1770 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1772 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1773 .setDescriptorCount(1)
1774 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1775 .setPImmutableSamplers(nullptr),
1776 vk::DescriptorSetLayoutBinding()
1778 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1779 .setDescriptorCount(texture_count)
1780 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1781 .setPImmutableSamplers(nullptr)};
1783 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1785 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1786 VERIFY(result == vk::Result::eSuccess);
1788 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1790 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1791 VERIFY(result == vk::Result::eSuccess);
1794 void Demo::prepare_descriptor_pool() {
1795 vk::DescriptorPoolSize const poolSizes[2] = {
1796 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1797 vk::DescriptorPoolSize()
1798 .setType(vk::DescriptorType::eCombinedImageSampler)
1799 .setDescriptorCount(swapchainImageCount * texture_count)};
1801 auto const descriptor_pool =
1802 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1804 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1805 VERIFY(result == vk::Result::eSuccess);
1808 void Demo::prepare_descriptor_set() {
1809 auto const alloc_info =
1810 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1812 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1814 vk::DescriptorImageInfo tex_descs[texture_count];
1815 for (uint32_t i = 0; i < texture_count; i++) {
1816 tex_descs[i].setSampler(textures[i].sampler);
1817 tex_descs[i].setImageView(textures[i].view);
1818 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1821 vk::WriteDescriptorSet writes[2];
1823 writes[0].setDescriptorCount(1);
1824 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1825 writes[0].setPBufferInfo(&buffer_info);
1827 writes[1].setDstBinding(1);
1828 writes[1].setDescriptorCount(texture_count);
1829 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1830 writes[1].setPImageInfo(tex_descs);
1832 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1833 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
1834 VERIFY(result == vk::Result::eSuccess);
1836 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1837 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1838 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1839 device.updateDescriptorSets(2, writes, 0, nullptr);
1843 void Demo::prepare_framebuffers() {
1844 vk::ImageView attachments[2];
1845 attachments[1] = depth.view;
1847 auto const fb_info = vk::FramebufferCreateInfo()
1848 .setRenderPass(render_pass)
1849 .setAttachmentCount(2)
1850 .setPAttachments(attachments)
1851 .setWidth((uint32_t)width)
1852 .setHeight((uint32_t)height)
1855 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1856 attachments[0] = swapchain_image_resources[i].view;
1857 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
1858 VERIFY(result == vk::Result::eSuccess);
1862 vk::ShaderModule Demo::prepare_fs() {
1863 const uint32_t fragShaderCode[] = {
1864 #include "cube.frag.inc"
1867 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
1869 return frag_shader_module;
1872 void Demo::prepare_pipeline() {
1873 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1874 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1875 VERIFY(result == vk::Result::eSuccess);
1877 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1878 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1879 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1881 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1883 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1885 // TODO: Where are pViewports and pScissors set?
1886 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1888 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1889 .setDepthClampEnable(VK_FALSE)
1890 .setRasterizerDiscardEnable(VK_FALSE)
1891 .setPolygonMode(vk::PolygonMode::eFill)
1892 .setCullMode(vk::CullModeFlagBits::eBack)
1893 .setFrontFace(vk::FrontFace::eCounterClockwise)
1894 .setDepthBiasEnable(VK_FALSE)
1895 .setLineWidth(1.0f);
1897 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1899 auto const stencilOp =
1900 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1902 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1903 .setDepthTestEnable(VK_TRUE)
1904 .setDepthWriteEnable(VK_TRUE)
1905 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1906 .setDepthBoundsTestEnable(VK_FALSE)
1907 .setStencilTestEnable(VK_FALSE)
1908 .setFront(stencilOp)
1909 .setBack(stencilOp);
1911 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1912 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1913 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1915 auto const colorBlendInfo =
1916 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1918 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1920 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1922 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1924 .setPStages(shaderStageInfo)
1925 .setPVertexInputState(&vertexInputInfo)
1926 .setPInputAssemblyState(&inputAssemblyInfo)
1927 .setPViewportState(&viewportInfo)
1928 .setPRasterizationState(&rasterizationInfo)
1929 .setPMultisampleState(&multisampleInfo)
1930 .setPDepthStencilState(&depthStencilInfo)
1931 .setPColorBlendState(&colorBlendInfo)
1932 .setPDynamicState(&dynamicStateInfo)
1933 .setLayout(pipeline_layout)
1934 .setRenderPass(render_pass);
1936 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1937 VERIFY(result == vk::Result::eSuccess);
1939 device.destroyShaderModule(frag_shader_module, nullptr);
1940 device.destroyShaderModule(vert_shader_module, nullptr);
1943 void Demo::prepare_render_pass() {
1944 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1945 // because at the start of the renderpass, we don't care about their contents.
1946 // At the start of the subpass, the color attachment's layout will be transitioned
1947 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1948 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1949 // the renderpass, the color attachment's layout will be transitioned to
1950 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1951 // the renderpass, no barriers are necessary.
1952 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1954 .setSamples(vk::SampleCountFlagBits::e1)
1955 .setLoadOp(vk::AttachmentLoadOp::eClear)
1956 .setStoreOp(vk::AttachmentStoreOp::eStore)
1957 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1958 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1959 .setInitialLayout(vk::ImageLayout::eUndefined)
1960 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1961 vk::AttachmentDescription()
1962 .setFormat(depth.format)
1963 .setSamples(vk::SampleCountFlagBits::e1)
1964 .setLoadOp(vk::AttachmentLoadOp::eClear)
1965 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1966 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1967 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1968 .setInitialLayout(vk::ImageLayout::eUndefined)
1969 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1971 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1973 auto const depth_reference =
1974 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1976 auto const subpass = vk::SubpassDescription()
1977 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1978 .setInputAttachmentCount(0)
1979 .setPInputAttachments(nullptr)
1980 .setColorAttachmentCount(1)
1981 .setPColorAttachments(&color_reference)
1982 .setPResolveAttachments(nullptr)
1983 .setPDepthStencilAttachment(&depth_reference)
1984 .setPreserveAttachmentCount(0)
1985 .setPPreserveAttachments(nullptr);
1987 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
1988 vk::SubpassDependency const dependencies[2] = {
1989 vk::SubpassDependency() // Depth buffer is shared between swapchain images
1990 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
1992 .setSrcStageMask(stages)
1993 .setDstStageMask(stages)
1994 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
1995 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
1996 .setDependencyFlags(vk::DependencyFlags()),
1997 vk::SubpassDependency() // Image layout transition
1998 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2000 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2001 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2002 .setSrcAccessMask(vk::AccessFlagBits())
2003 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2004 .setDependencyFlags(vk::DependencyFlags()),
2007 auto const rp_info = vk::RenderPassCreateInfo()
2008 .setAttachmentCount(2)
2009 .setPAttachments(attachments)
2011 .setPSubpasses(&subpass)
2012 .setDependencyCount(2)
2013 .setPDependencies(dependencies);
2015 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2016 VERIFY(result == vk::Result::eSuccess);
2019 vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2020 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2022 vk::ShaderModule module;
2023 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2024 VERIFY(result == vk::Result::eSuccess);
2029 void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2033 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2034 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2037 tex_obj->tex_width = tex_width;
2038 tex_obj->tex_height = tex_height;
2040 auto const buffer_create_info = vk::BufferCreateInfo()
2041 .setSize(tex_width * tex_height * 4)
2042 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2043 .setSharingMode(vk::SharingMode::eExclusive)
2044 .setQueueFamilyIndexCount(0)
2045 .setPQueueFamilyIndices(nullptr);
2047 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2048 VERIFY(result == vk::Result::eSuccess);
2050 vk::MemoryRequirements mem_reqs;
2051 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2053 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2054 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2056 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2057 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2058 VERIFY(pass == true);
2060 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2061 VERIFY(result == vk::Result::eSuccess);
2063 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2064 VERIFY(result == vk::Result::eSuccess);
2066 vk::SubresourceLayout layout;
2067 layout.rowPitch = tex_width * 4;
2068 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2069 VERIFY(data.result == vk::Result::eSuccess);
2071 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2072 fprintf(stderr, "Error loading texture: %s\n", filename);
2075 device.unmapMemory(tex_obj->mem);
2078 void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2079 vk::MemoryPropertyFlags required_props) {
2082 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2083 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2086 tex_obj->tex_width = tex_width;
2087 tex_obj->tex_height = tex_height;
2089 auto const image_create_info = vk::ImageCreateInfo()
2090 .setImageType(vk::ImageType::e2D)
2091 .setFormat(vk::Format::eR8G8B8A8Unorm)
2092 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2095 .setSamples(vk::SampleCountFlagBits::e1)
2098 .setSharingMode(vk::SharingMode::eExclusive)
2099 .setQueueFamilyIndexCount(0)
2100 .setPQueueFamilyIndices(nullptr)
2101 .setInitialLayout(vk::ImageLayout::ePreinitialized);
2103 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2104 VERIFY(result == vk::Result::eSuccess);
2106 vk::MemoryRequirements mem_reqs;
2107 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
2109 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2110 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2112 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2113 VERIFY(pass == true);
2115 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2116 VERIFY(result == vk::Result::eSuccess);
2118 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2119 VERIFY(result == vk::Result::eSuccess);
2121 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2122 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2123 vk::SubresourceLayout layout;
2124 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
2126 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2127 VERIFY(data.result == vk::Result::eSuccess);
2129 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2130 fprintf(stderr, "Error loading texture: %s\n", filename);
2133 device.unmapMemory(tex_obj->mem);
2136 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2139 void Demo::prepare_textures() {
2140 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2141 vk::FormatProperties props;
2142 gpu.getFormatProperties(tex_format, &props);
2144 for (uint32_t i = 0; i < texture_count; i++) {
2145 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2146 /* Device can texture using linear textures */
2147 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2148 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2149 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2150 // shader to run until layout transition completes
2151 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2152 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2153 vk::PipelineStageFlagBits::eFragmentShader);
2154 staging_texture.image = vk::Image();
2155 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2156 /* Must use staging buffer to copy linear texture to optimized */
2158 prepare_texture_buffer(tex_files[i], &staging_texture);
2160 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2161 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2162 vk::MemoryPropertyFlagBits::eDeviceLocal);
2164 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2165 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2166 vk::PipelineStageFlagBits::eTransfer);
2168 auto const subresource = vk::ImageSubresourceLayers()
2169 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2171 .setBaseArrayLayer(0)
2174 auto const copy_region =
2175 vk::BufferImageCopy()
2177 .setBufferRowLength(staging_texture.tex_width)
2178 .setBufferImageHeight(staging_texture.tex_height)
2179 .setImageSubresource(subresource)
2180 .setImageOffset({0, 0, 0})
2181 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
2183 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, ©_region);
2185 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2186 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2187 vk::PipelineStageFlagBits::eFragmentShader);
2189 assert(!"No support for R8G8B8A8_UNORM as texture image format");
2192 auto const samplerInfo = vk::SamplerCreateInfo()
2193 .setMagFilter(vk::Filter::eNearest)
2194 .setMinFilter(vk::Filter::eNearest)
2195 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2196 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2197 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2198 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2199 .setMipLodBias(0.0f)
2200 .setAnisotropyEnable(VK_FALSE)
2201 .setMaxAnisotropy(1)
2202 .setCompareEnable(VK_FALSE)
2203 .setCompareOp(vk::CompareOp::eNever)
2206 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2207 .setUnnormalizedCoordinates(VK_FALSE);
2209 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2210 VERIFY(result == vk::Result::eSuccess);
2212 auto const viewInfo = vk::ImageViewCreateInfo()
2213 .setImage(textures[i].image)
2214 .setViewType(vk::ImageViewType::e2D)
2215 .setFormat(tex_format)
2216 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2218 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2219 VERIFY(result == vk::Result::eSuccess);
2223 vk::ShaderModule Demo::prepare_vs() {
2224 const uint32_t vertShaderCode[] = {
2225 #include "cube.vert.inc"
2228 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2230 return vert_shader_module;
2233 void Demo::resize() {
2236 // Don't react to resize until after first initialization.
2241 // In order to properly resize the window, we must re-create the
2243 // AND redo the command buffers, etc.
2245 // First, perform part of the cleanup() function:
2247 auto result = device.waitIdle();
2248 VERIFY(result == vk::Result::eSuccess);
2250 for (i = 0; i < swapchainImageCount; i++) {
2251 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2254 device.destroyDescriptorPool(desc_pool, nullptr);
2256 device.destroyPipeline(pipeline, nullptr);
2257 device.destroyPipelineCache(pipelineCache, nullptr);
2258 device.destroyRenderPass(render_pass, nullptr);
2259 device.destroyPipelineLayout(pipeline_layout, nullptr);
2260 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2262 for (i = 0; i < texture_count; i++) {
2263 device.destroyImageView(textures[i].view, nullptr);
2264 device.destroyImage(textures[i].image, nullptr);
2265 device.freeMemory(textures[i].mem, nullptr);
2266 device.destroySampler(textures[i].sampler, nullptr);
2269 device.destroyImageView(depth.view, nullptr);
2270 device.destroyImage(depth.image, nullptr);
2271 device.freeMemory(depth.mem, nullptr);
2273 for (i = 0; i < swapchainImageCount; i++) {
2274 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2275 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2276 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2277 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
2278 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2281 device.destroyCommandPool(cmd_pool, nullptr);
2282 if (separate_present_queue) {
2283 device.destroyCommandPool(present_cmd_pool, nullptr);
2286 // Second, re-perform the prepare() function, which will re-create the
2291 void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2292 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2295 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2296 vk::AccessFlags flags;
2299 case vk::ImageLayout::eTransferDstOptimal:
2300 // Make sure anything that was copying from this image has
2302 flags = vk::AccessFlagBits::eTransferWrite;
2304 case vk::ImageLayout::eColorAttachmentOptimal:
2305 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2307 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2308 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2310 case vk::ImageLayout::eShaderReadOnlyOptimal:
2311 // Make sure any Copy or CPU writes to image are flushed
2312 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2314 case vk::ImageLayout::eTransferSrcOptimal:
2315 flags = vk::AccessFlagBits::eTransferRead;
2317 case vk::ImageLayout::ePresentSrcKHR:
2318 flags = vk::AccessFlagBits::eMemoryRead;
2327 auto const barrier = vk::ImageMemoryBarrier()
2328 .setSrcAccessMask(srcAccessMask)
2329 .setDstAccessMask(DstAccessMask(newLayout))
2330 .setOldLayout(oldLayout)
2331 .setNewLayout(newLayout)
2332 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2333 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2335 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2337 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2340 void Demo::update_data_buffer() {
2342 mat4x4_mul(VP, projection_matrix, view_matrix);
2344 // Rotate around the Y axis
2346 mat4x4_dup(Model, model_matrix);
2347 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2350 mat4x4_mul(MVP, VP, model_matrix);
2352 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
2355 /* Convert ppm image data from header file into RGBA texture image */
2356 #include "lunarg.ppm.h"
2357 bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height) {
2360 cPtr = (char *)lunarg_ppm;
2361 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
2364 while (strncmp(cPtr++, "\n", 1))
2366 sscanf(cPtr, "%u %u", width, height);
2367 if (rgba_data == NULL) {
2370 while (strncmp(cPtr++, "\n", 1))
2372 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
2375 while (strncmp(cPtr++, "\n", 1))
2377 for (int y = 0; y < *height; y++) {
2378 uint8_t *rowPtr = rgba_data;
2379 for (int x = 0; x < *width; x++) {
2380 memcpy(rowPtr, cPtr, 3);
2381 rowPtr[3] = 255; /* Alpha of 1 */
2385 rgba_data += layout->rowPitch;
2390 bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2391 // Search memtypes to find first index with those properties
2392 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2393 if ((typeBits & 1) == 1) {
2394 // Type is available, does it match user properties?
2395 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2403 // No memory types matched, return failure
2407 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2416 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2417 PostQuitMessage(validation_error);
2421 void Demo::create_window() {
2422 WNDCLASSEX win_class;
2424 // Initialize the window class structure:
2425 win_class.cbSize = sizeof(WNDCLASSEX);
2426 win_class.style = CS_HREDRAW | CS_VREDRAW;
2427 win_class.lpfnWndProc = WndProc;
2428 win_class.cbClsExtra = 0;
2429 win_class.cbWndExtra = 0;
2430 win_class.hInstance = connection; // hInstance
2431 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2432 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2433 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2434 win_class.lpszMenuName = nullptr;
2435 win_class.lpszClassName = name;
2436 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2438 // Register window class:
2439 if (!RegisterClassEx(&win_class)) {
2440 // It didn't work, so try to give a useful error:
2441 printf("Unexpected error trying to start the application!\n");
2446 // Create window with the registered class:
2447 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2448 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2449 window = CreateWindowEx(0,
2452 WS_OVERLAPPEDWINDOW | // window style
2453 WS_VISIBLE | WS_SYSMENU,
2454 100, 100, // x/y coords
2455 wr.right - wr.left, // width
2456 wr.bottom - wr.top, // height
2457 nullptr, // handle to parent
2458 nullptr, // handle to menu
2459 connection, // hInstance
2460 nullptr); // no extra parameters
2463 // It didn't work, so try to give a useful error:
2464 printf("Cannot create a window in which to draw!\n");
2469 // Window client area size must be at least 1 pixel high, to prevent
2471 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2472 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2474 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2476 void Demo::create_xlib_window() {
2477 const char *display_envar = getenv("DISPLAY");
2478 if (display_envar == nullptr || display_envar[0] == '\0') {
2479 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2485 display = XOpenDisplay(nullptr);
2486 long visualMask = VisualScreenMask;
2487 int numberOfVisuals;
2488 XVisualInfo vInfoTemplate = {};
2489 vInfoTemplate.screen = DefaultScreen(display);
2490 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2492 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2494 XSetWindowAttributes windowAttributes = {};
2495 windowAttributes.colormap = colormap;
2496 windowAttributes.background_pixel = 0xFFFFFFFF;
2497 windowAttributes.border_pixel = 0;
2498 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2501 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2502 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2504 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2505 XMapWindow(display, xlib_window);
2507 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2510 void Demo::handle_xlib_event(const XEvent *event) {
2511 switch (event->type) {
2513 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2518 switch (event->xkey.keycode) {
2522 case 0x71: // left arrow key
2523 spin_angle -= spin_increment;
2525 case 0x72: // right arrow key
2526 spin_angle += spin_increment;
2528 case 0x41: // space bar
2533 case ConfigureNotify:
2534 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2535 width = event->xconfigure.width;
2536 height = event->xconfigure.height;
2545 void Demo::run_xlib() {
2550 XNextEvent(display, &event);
2551 handle_xlib_event(&event);
2553 while (XPending(display) > 0) {
2554 XNextEvent(display, &event);
2555 handle_xlib_event(&event);
2561 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2566 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2568 void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2569 uint8_t event_code = event->response_type & 0x7f;
2570 switch (event_code) {
2572 // TODO: Resize window
2574 case XCB_CLIENT_MESSAGE:
2575 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2579 case XCB_KEY_RELEASE: {
2580 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2582 switch (key->detail) {
2586 case 0x71: // left arrow key
2587 spin_angle -= spin_increment;
2589 case 0x72: // right arrow key
2590 spin_angle += spin_increment;
2592 case 0x41: // space bar
2597 case XCB_CONFIGURE_NOTIFY: {
2598 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2599 if ((width != cfg->width) || (height != cfg->height)) {
2601 height = cfg->height;
2610 void Demo::run_xcb() {
2611 xcb_flush(connection);
2614 xcb_generic_event_t *event;
2617 event = xcb_wait_for_event(connection);
2619 event = xcb_poll_for_event(connection);
2622 handle_xcb_event(event);
2624 event = xcb_poll_for_event(connection);
2629 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2635 void Demo::create_xcb_window() {
2636 uint32_t value_mask, value_list[32];
2638 xcb_window = xcb_generate_id(connection);
2640 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2641 value_list[0] = screen->black_pixel;
2642 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2644 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2645 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2647 /* Magic code that will send notification when window is destroyed */
2648 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2649 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2651 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2652 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2654 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2658 xcb_map_window(connection, xcb_window);
2660 // Force the x/y coordinates to 100,100 results are identical in
2663 const uint32_t coords[] = {100, 100};
2664 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2666 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2671 wl_display_dispatch(display);
2673 wl_display_dispatch_pending(display);
2674 update_data_buffer();
2677 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2684 void Demo::create_window() {
2685 window = wl_compositor_create_surface(compositor);
2687 printf("Can not create wayland_surface from compositor!\n");
2692 shell_surface = wl_shell_get_shell_surface(shell, window);
2693 if (!shell_surface) {
2694 printf("Can not get shell_surface from wayland_surface!\n");
2699 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2700 wl_shell_surface_set_toplevel(shell_surface);
2701 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
2703 #elif defined(VK_USE_PLATFORM_METAL_EXT)
2707 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2711 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2713 vk::Result Demo::create_display_surface() {
2715 uint32_t display_count;
2716 uint32_t mode_count;
2717 uint32_t plane_count;
2718 vk::DisplayPropertiesKHR display_props;
2719 vk::DisplayKHR display;
2720 vk::DisplayModePropertiesKHR mode_props;
2721 vk::DisplayPlanePropertiesKHR *plane_props;
2722 vk::Bool32 found_plane = VK_FALSE;
2723 uint32_t plane_index;
2724 vk::Extent2D image_extent;
2726 // Get the first display
2727 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2728 VERIFY(result == vk::Result::eSuccess);
2730 if (display_count == 0) {
2731 printf("Cannot find any display!\n");
2737 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2738 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2740 display = display_props.display;
2742 // Get the first mode of the display
2743 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2744 VERIFY(result == vk::Result::eSuccess);
2746 if (mode_count == 0) {
2747 printf("Cannot find any mode for the display!\n");
2753 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2754 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2756 // Get the list of planes
2757 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2758 VERIFY(result == vk::Result::eSuccess);
2760 if (plane_count == 0) {
2761 printf("Cannot find any plane!\n");
2766 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2767 VERIFY(plane_props != nullptr);
2769 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2770 VERIFY(result == vk::Result::eSuccess);
2772 // Find a plane compatible with the display
2773 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2774 uint32_t supported_count;
2775 vk::DisplayKHR *supported_displays;
2777 // Disqualify planes that are bound to a different display
2778 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2782 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
2783 VERIFY(result == vk::Result::eSuccess);
2785 if (supported_count == 0) {
2789 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2790 VERIFY(supported_displays != nullptr);
2792 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
2793 VERIFY(result == vk::Result::eSuccess);
2795 for (uint32_t i = 0; i < supported_count; i++) {
2796 if (supported_displays[i] == display) {
2797 found_plane = VK_TRUE;
2802 free(supported_displays);
2810 printf("Cannot find a plane compatible with the display!\n");
2817 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2818 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2819 // Find a supported alpha mode
2820 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2821 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2822 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2823 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2824 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2825 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2827 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2828 if (planeCaps.supportedAlpha & alphaModes[i]) {
2829 alphaMode = alphaModes[i];
2834 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2835 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2837 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2838 .setDisplayMode(mode_props.displayMode)
2839 .setPlaneIndex(plane_index)
2840 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2841 .setGlobalAlpha(1.0f)
2842 .setAlphaMode(alphaMode)
2843 .setImageExtent(image_extent);
2845 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2848 void Demo::run_display() {
2853 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2861 // Include header required for parsing the command line options.
2862 #include <shellapi.h>
2866 // MS-Windows event handling function:
2867 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2870 PostQuitMessage(validation_error);
2875 case WM_GETMINMAXINFO: // set window's minimum size
2876 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2881 // Resize the application to the new window size, except when
2882 // it was minimized. Vulkan doesn't support images or swapchains
2883 // with width=0 and height=0.
2884 if (wParam != SIZE_MINIMIZED) {
2885 demo.width = lParam & 0xffff;
2886 demo.height = (lParam & 0xffff0000) >> 16;
2893 PostQuitMessage(validation_error);
2896 demo.spin_angle -= demo.spin_increment;
2899 demo.spin_angle += demo.spin_increment;
2902 demo.pause = !demo.pause;
2910 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2913 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
2914 // TODO: Gah.. refactor. This isn't 1989.
2916 bool done; // flag saying when app is complete
2920 // Ensure wParam is initialized.
2923 // Use the CommandLine functions to get the command line arguments.
2924 // Unfortunately, Microsoft outputs
2925 // this information as wide characters for Unicode, and we simply want the
2926 // Ascii version to be compatible
2927 // with the non-Windows side. So, we have to convert the information to
2928 // Ascii character strings.
2929 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
2930 if (nullptr == commandLineArgs) {
2935 argv = (char **)malloc(sizeof(char *) * argc);
2936 if (argv == nullptr) {
2939 for (int iii = 0; iii < argc; iii++) {
2940 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2941 size_t numConverted = 0;
2943 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
2944 if (argv[iii] != nullptr) {
2945 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
2953 demo.init(argc, argv);
2955 // Free up the items we had to allocate for the command line arguments.
2956 if (argc > 0 && argv != nullptr) {
2957 for (int iii = 0; iii < argc; iii++) {
2958 if (argv[iii] != nullptr) {
2965 demo.connection = hInstance;
2966 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
2967 demo.create_window();
2968 demo.init_vk_swapchain();
2972 done = false; // initialize loop condition variable
2974 // main message loop
2977 const BOOL succ = WaitMessage();
2980 const auto &suppress_popups = demo.suppress_popups;
2981 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
2985 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
2986 if (msg.message == WM_QUIT) // check for a quit message
2988 done = true; // if found, quit app
2990 /* Translate and dispatch to event queue*/
2991 TranslateMessage(&msg);
2992 DispatchMessage(&msg);
2994 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2999 return (int)msg.wParam;
3004 int main(int argc, char **argv) {
3007 demo.init(argc, argv);
3009 #if defined(VK_USE_PLATFORM_XCB_KHR)
3010 demo.create_xcb_window();
3011 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3012 demo.use_xlib = true;
3013 demo.create_xlib_window();
3014 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3015 demo.create_window();
3018 demo.init_vk_swapchain();
3022 #if defined(VK_USE_PLATFORM_XCB_KHR)
3024 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3026 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3028 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3034 return validation_error;
3037 #elif defined(VK_USE_PLATFORM_METAL_EXT)
3039 // Global function invoked from NS or UI views and controllers to create demo
3040 static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
3041 demo.init(argc, (char **)argv);
3042 demo.caMetalLayer = caMetalLayer;
3043 demo.init_vk_swapchain();
3045 demo.spin_angle = 0.4f;
3049 #error "Platform not supported"