fixed swapchain sync for standard win, needs recreation at resize
[vkrt] / src / main.cc
1 #include <stdio.h>
2
3 #define GLFW_INCLUDE_VULKAN
4 #include <GLFW/glfw3.h>
5
6 #include <assert.h>
7 #include <stdlib.h>
8 #include <string.h>
9
10 #include <vector>
11
12 #include <gmath/gmath.h>
13
14 /* extern "C": vulkan framework */
15 #include "vk.h"
16 #include "util.h"
17
18 /* C++ */
19 #include "camera.h"
20
21 /* defines */
22 #define FRAME_LAG 2
23 #define FENCE_TIMEOUT UINT64_MAX
24
25 /**************************/
26 /* static glfw callbacks */
27 /**************************/
28
29 static void
30 clb_key(GLFWwindow *win, int key, int scancode, int action, int mods);
31
32 static void
33 clb_reshape(GLFWwindow *win, int width, int height);
34
35 static void
36 clb_motion(GLFWwindow *win, double x, double y);
37
38 static void
39 clb_mouse(GLFWwindow *win, int button, int action, int mods);
40
41 /**************************/
42 /* static functions */
43 /**************************/
44
45 /* init, cleanup, display */
46
47 static bool
48 init();
49
50 static void
51 cleanup();
52
53 static void
54 display();
55
56 /* vulkan, glfw */
57
58 static bool
59 vk_init();
60
61 static bool
62 vk_create_sync_objects();
63
64 static void
65 vk_cleanup();
66
67 /***************************/
68 /* static/global variables */
69 /***************************/
70
71 static GLFWwindow *win;
72 /* static bool redraw_pending; */
73 static bool move_camera;
74
75 /* camera */
76 static float cam_phi = 25;
77 static float cam_theta = 0;
78 static float cam_dist = 16;
79 static Vec3 cam_pos;
80
81 static OrbitCamera *camera;
82
83 static float aspect;
84 static Mat4 mproj;
85
86 /* win etc */
87 static int win_w = 800;
88 static int win_h = 600;
89
90 /* vulkan */
91 static bool vk_enable_layers = true;
92 static struct vk_ctx vk_core;
93 static VkSurfaceKHR vk_surf;
94
95 static struct vk_swapchain vk_chain;
96 static uint32_t vk_current_image;
97 static int vk_frame_idx;
98 static std::vector<VkFramebuffer>vk_framebuffers;
99
100 /* for the moment: one cmd buffer per swapchain image */
101 static std::vector<VkCommandBuffer>vk_cmd_buffers;
102 static std::vector<VkFence>vk_fences;
103 static struct vk_semaphores vk_semas[FRAME_LAG];
104
105 /* FIXME make them part of each object's functions/params */
106 static struct vk_renderer vk_rnd;
107 static struct vk_attachment vk_depth_att;
108 static float vk_fb_color[4] = { 0.0, 0.0, 0.5, 1.0 };
109
110 /* empty for as long as we hardcode the vertices in the vertex shader */
111 #if 0
112 static struct vk_vertex_info vk_vert_info;
113 #endif
114
115 int main(int argc, char** argv)
116 {
117     atexit(cleanup);
118
119     /***********************************************************
120      * GLFW
121      ***********************************************************/
122
123     if (!glfwInit()) {
124         fprintf(stderr, "Failed to initialize GLFW.\n");
125         return 1;
126     }
127
128     if (glfwVulkanSupported() != GLFW_TRUE) {
129         fprintf(stderr, "Vulkan is not supported on this device.\n");
130         return false;
131     }
132
133     glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
134     glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
135     if (!(win = glfwCreateWindow(win_w, win_h, "helloworld rt", 0, 0))) {
136         fprintf(stderr, "Failed to create GLFW window\n");
137         return false;
138     }
139
140     glfwSetKeyCallback(win, clb_key);
141     glfwSetWindowSizeCallback(win, clb_reshape);
142     glfwSetCursorPosCallback(win, clb_motion);
143     glfwSetMouseButtonCallback(win, clb_mouse);
144
145     /***********************************************************
146      * VULKAN context
147      ***********************************************************/
148
149     if (!vk_init_ctx_for_rendering(&vk_core, true, vk_enable_layers)) {
150         fprintf(stderr, "Failed to initialize Vulkan context.\n");
151         return false;
152     }
153
154     /***********************************************************
155      * XCB/GLFW surface
156      ***********************************************************/
157
158     glfwGetFramebufferSize(win, &win_h, &win_h);
159     if (glfwCreateWindowSurface(vk_core.inst, win, 0, &vk_surf)
160             != VK_SUCCESS) {
161         fprintf(stderr, "Failed to create XCB surface.\n");
162         return false;
163     }
164
165     /***********************************************************
166      * Initialize Vulkan structs
167      ***********************************************************/
168
169     if (!vk_init()) {
170         return 1;
171     }
172
173     /***********************************************************
174      * Initialize program objects, classes etc
175      ***********************************************************/
176
177     if (!init()) {
178         return 1;
179     }
180
181     /***********************************************************
182      * Rendering loop
183      ***********************************************************/
184
185         while(!glfwWindowShouldClose(win)) {
186                 glfwPollEvents();
187                 display();
188         }
189
190     vkDeviceWaitIdle(vk_core.dev);
191     return 0;
192 }
193
194 /* static functions */
195
196 static bool
197 vk_init()
198 {
199     /* create swapchain */
200     if (!vk_create_swapchain(&vk_core, win_w, win_h, false, vk_surf, 0, &vk_chain)) {
201         fprintf(stderr, "No swapchain was created.\n");
202         return false;
203     }
204
205     if (vk_chain.swapchain == VK_NULL_HANDLE) {
206         fprintf(stderr, "Invalid swapchain handle.\n");
207         return false;
208     }
209
210     if (!vk_create_sync_objects()) {
211         fprintf(stderr, "Failed to create sync objects.\n");
212         return false;
213     }
214
215     /* FIXME for the moment one cmd buf.
216      * But most probably I need to change this later. */
217     VkCommandBuffer cmd_buf;
218     if (!(cmd_buf = vk_create_cmd_buffer(&vk_core))) {
219         fprintf(stderr, "Failed to create command buffer: %d.\n", 0);
220         return false;
221     }
222     vk_cmd_buffers.push_back(cmd_buf);
223
224     /* FIXME: this part is going to be part of each object's
225      * renderpass and pipeline */
226
227     /* create depth attachment (for the moment we are going to use this
228      * for all images */
229     if (!vk_fill_image_props(&vk_core,
230                              win_w, win_h, 1,
231                              1, 1, 1,
232                              VK_FORMAT_D32_SFLOAT_S8_UINT,
233                              VK_IMAGE_TILING_OPTIMAL,
234                              VK_IMAGE_LAYOUT_UNDEFINED,
235                              VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
236                              false, true, false,
237                              &vk_depth_att.props)) {
238         fprintf(stderr, "Unsupported depth image properties\n");
239         return false;
240     }
241     if (!vk_create_image(&vk_core, &vk_depth_att.props, &vk_depth_att.obj)) {
242         fprintf(stderr, "Failed to create depth attachment.\n");
243         return false;
244     }
245     if(!vk_create_image_view(&vk_core, vk_depth_att.obj.img, VK_IMAGE_VIEW_TYPE_2D,
246                              vk_depth_att.props.format, false,
247                              &vk_depth_att.obj.img_view)) {
248         fprintf(stderr, "Failed to create image view for depth attachment.\n");
249         return false;
250     }
251
252     /* load shaders */
253     int vsz, fsz;
254     char *vsdr = sdr_load("data/main.vert.spv", &vsz);
255     char *fsdr = sdr_load("data/main.frag.spv", &fsz);
256
257     /* create renderer */
258     if (!vk_create_renderer(&vk_core,
259                             vsdr, vsz, fsdr, fsz,
260                             win_w, win_h, 1,
261                             true, false,
262                             1, &vk_chain.img_props, &vk_depth_att.props,
263                             0, &vk_rnd)) {
264         goto fail;
265     }
266
267     vk_framebuffers.resize(vk_chain.num_images, VK_NULL_HANDLE);
268     for (uint32_t i = 0; i < vk_chain.num_images; i++) {
269         if (!vk_create_framebuffer(&vk_core,
270                                    win_w, win_h, 1,
271                                    &vk_chain.views[i],
272                                    &vk_depth_att.obj.img_view,
273                                    vk_rnd.renderpass,
274                                    &vk_framebuffers[i]))
275         goto fail;
276     }
277
278     /* record cmd buffer FIXME:
279      * should move this and make it part of each renderer
280      * also add all other stuff needed like uniforms
281      * descriptor sets spec constants push constants etc
282      * renderer
283      */
284
285     free(vsdr);
286     free(fsdr);
287
288     return true;
289
290 fail:
291     free(vsdr);
292     free(fsdr);
293
294     return false;
295 }
296
297 static bool
298 init()
299 {
300     camera = new OrbitCamera;
301     return true;
302 }
303
304 static void
305 cleanup()
306 {
307     delete camera;
308
309     vk_cleanup();
310 }
311
312 /* FIXME */
313 static int count;
314 static void
315 display()
316 {
317     vkWaitForFences(vk_core.dev, 1, &vk_fences[vk_frame_idx], VK_TRUE, UINT64_MAX);
318     vkResetFences(vk_core.dev, 1, &vk_fences[vk_frame_idx]);
319
320     VkResult err;
321     do {
322         err = vkAcquireNextImageKHR(vk_core.dev, vk_chain.swapchain,
323                                     UINT64_MAX,
324                                     vk_semas[vk_frame_idx].frame_ready,
325                                     0, &vk_current_image);
326         switch(err) {
327         case VK_ERROR_OUT_OF_DATE_KHR:
328             fprintf(stderr, "acquire next image error: VK_ERROR_OUT_OF_DATE_KHR.\n");
329             abort();
330             break;
331         case VK_SUBOPTIMAL_KHR:
332             fprintf(stderr, "AcquireNextImageKHR returned VK_SUBOPTIMAL_KHR, ignored.\n");
333             abort();
334             break;
335         case VK_ERROR_SURFACE_LOST_KHR:
336             vkDestroySurfaceKHR(vk_core.inst, vk_surf, 0);
337             if (glfwCreateWindowSurface(vk_core.inst, win, 0, &vk_surf) !=
338                     VK_SUCCESS) {
339                 fprintf(stderr, "Failed to recreate GLFW/XCB surface.\n");
340             }
341             abort();
342             break;
343         default:
344             assert(!err);
345             break;
346         }
347     } while (err != VK_SUCCESS);
348
349     /* FIXME update buffer data */
350     if (!vk_record_cmd_buffer(&vk_core, vk_cmd_buffers[0],
351                 &vk_rnd, 0,
352                 4, vk_fb_color,
353                 vk_framebuffers[vk_current_image],
354                 2, 0,
355                 0, 0, win_w, win_h)) {
356         fprintf(stderr, "Failed to record command buffer.\n");
357         abort();
358     }
359
360     /* each object should have a command buffer renderpass etc? */
361     VkSubmitInfo sinfo;
362     VkPipelineStageFlags wait_stages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
363
364     memset(&sinfo, 0, sizeof sinfo);
365     sinfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
366     sinfo.waitSemaphoreCount = 1;
367     sinfo.pWaitSemaphores = &vk_semas[vk_frame_idx].frame_ready;
368     sinfo.pWaitDstStageMask = &wait_stages;
369     sinfo.commandBufferCount = 1;
370     sinfo.pCommandBuffers = &vk_cmd_buffers[0];
371     sinfo.signalSemaphoreCount = 1;
372         sinfo.pSignalSemaphores = &vk_semas[vk_frame_idx].frame_done;
373
374     if (vkQueueSubmit(vk_core.queue, 1, &sinfo, vk_fences[vk_frame_idx]) != 0) {
375         fprintf(stderr, "Failed to submit draw commands.\n");
376         abort();
377     }
378
379     if (vkQueueWaitIdle(vk_core.queue) != VK_SUCCESS) {
380         fprintf(stderr, "Failed to wait idle.\n");
381         abort();
382     }
383
384     if (!vk_queue_present(&vk_chain, vk_core.queue, vk_current_image,
385                           vk_semas[vk_frame_idx].frame_done)) {
386         abort();
387     }
388
389     vk_frame_idx = (vk_frame_idx + 1) % FRAME_LAG;
390
391     printf("display %d\n", count++);
392     printf("current image %u\n", vk_current_image);
393     printf("frame idx %d\n", vk_frame_idx);
394 }
395
396 static void
397 vk_cleanup()
398 {
399     vk_destroy_image(&vk_core, &vk_depth_att.obj);
400     vk_destroy_renderer(&vk_core, &vk_rnd);
401
402     for (size_t i = 0; i < vk_framebuffers.size(); i++) {
403         vkDestroyFramebuffer(vk_core.dev, vk_framebuffers[i], 0);
404     }
405     vk_framebuffers.clear();
406
407     glfwDestroyWindow(win);
408
409     if (vk_chain.swapchain) {
410         vk_destroy_swapchain(&vk_core, &vk_chain);
411         vkDestroySurfaceKHR(vk_core.inst, vk_surf, 0);
412     }
413
414     if (vk_enable_layers)
415         return;
416
417     vk_destroy_cmd_buffers(&vk_core, vk_cmd_buffers.size(), vk_cmd_buffers.data());
418     vk_cmd_buffers.clear();
419
420     vk_destroy_fences(&vk_core, vk_fences.size(), vk_fences.data());
421     vk_fences.clear();
422
423     for (int i = 0; i < FRAME_LAG; i++)
424         vk_destroy_semaphores(&vk_core, &vk_semas[i]);
425
426     for (size_t i = 0; i < vk_cmd_buffers.size(); i++)
427         vk_destroy_cmd_buffers(&vk_core, vk_cmd_buffers.size(), vk_cmd_buffers.data());
428     vk_cmd_buffers.clear();
429
430     glfwTerminate();
431
432     vk_cleanup_ctx(&vk_core);
433 }
434
435 static bool
436 vk_create_sync_objects()
437 {
438     VkFenceCreateInfo finfo;
439     memset(&finfo, 0, sizeof finfo);
440     finfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
441     finfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
442
443     VkSemaphoreCreateInfo sinfo;
444     memset(&sinfo, 0, sizeof sinfo);
445     sinfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
446
447     vk_fences.resize(FRAME_LAG, VK_NULL_HANDLE);
448
449     for (int i = 0; i < FRAME_LAG; i++) {
450         if (vkCreateFence(vk_core.dev, &finfo, 0, &vk_fences[i]) != VK_SUCCESS) {
451             fprintf(stderr, "Failed to create fence: %d\n", i);
452             return false;
453         }
454
455         if (vkCreateSemaphore(vk_core.dev, &sinfo, 0, &vk_semas[i].frame_ready) != VK_SUCCESS) {
456             fprintf(stderr, "Failed to create frame_ready semaphore: %d\n", i);
457             return false;
458         }
459
460         if (vkCreateSemaphore(vk_core.dev, &sinfo, 0, &vk_semas[i].frame_done) != VK_SUCCESS) {
461             fprintf(stderr, "Failed to create frame_done semaphore: %d\n", i);
462             return false;
463         }
464     }
465
466     return true;
467 }
468
469 /* glfw callbacks */
470
471 static void
472 clb_reshape(GLFWwindow *win,
473             int width,
474             int height)
475 {
476     aspect = (float)width / (float)height;
477     mproj = calc_projection_matrix(45, aspect, 0.5, 1000.0f);
478
479     /* FIXME near and far clipping planes */
480     vk_set_viewport(&vk_core, vk_cmd_buffers[0],
481                     0, 0, win_w, win_h, 0.0f, 1.0f);
482     win_w = width;
483     win_h = height;
484 }
485
486 static void
487 clb_key(GLFWwindow *win, int key, int scancode,
488         int action, int mods)
489 {
490     if (action == GLFW_REPEAT) return;
491
492     if (action == GLFW_PRESS) {
493         switch(key) {
494         case GLFW_KEY_ESCAPE:
495             glfwSetWindowShouldClose(win, GLFW_TRUE);
496             exit(0);
497         case ' ':
498             move_camera = !move_camera;
499             break;
500         default:
501             break;
502         }
503     }
504 }
505
506 static double prev_x, prev_y;
507 static bool button[8];
508
509 static void
510 clb_motion(GLFWwindow *win,
511            double x,
512            double y)
513 {
514         double dx = x - prev_x;
515         double dy = y - prev_y;
516
517         prev_x = x;
518         prev_y = y;
519
520         if(button[0]) {
521                 cam_theta += dx * 0.5;
522                 cam_phi += dy * 0.5;
523
524                 if(cam_phi < 0)
525                         cam_phi = 0;
526                 if(cam_phi > 90)
527                         cam_phi = 90;
528         }
529
530         if(button[1]) {
531                 cam_dist += dy * 0.1;
532                 if(cam_dist < 0.0) {
533                         cam_dist = 0.0;
534                 }
535         }
536 }
537
538 static void
539 clb_mouse(GLFWwindow *win,
540           int button,
541           int action,
542           int mods)
543 {
544 }