-
Notifications
You must be signed in to change notification settings - Fork 1
/
scene.cc
257 lines (215 loc) · 10.4 KB
/
scene.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Modifications copyright (C) 2020 Leonardo Romor <[email protected]>
//
// This file contains the basic ingredients to render a basic wireframed scene.
// This simple scene allows you to add meshes and a freely "movable" camera.
#include <glm/ext/quaternion_geometric.hpp>
#include <unistd.h>
#include <iostream>
#include <optional>
#include <X11/Xlib.h>
#include <vulkan/vulkan.hpp>
#include <numeric>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include "vulkan-core.h"
#include "scene.h"
#define FENCE_TIMEOUT 100000000
Scene::Scene(space::core::VkAppContext *vk_ctx, Camera *camera, const QueryExtentCallback &fn)
: vk_ctx_(vk_ctx), QueryExtent(fn), current_buffer_(0),
draw_fence_(vk_ctx->device->createFenceUnique(vk::FenceCreateInfo())),
camera_(camera) {}
void Scene::Init() {
vk::UniqueDevice &device = vk_ctx_->device;
const uint32_t graphics_queue_family_index = vk_ctx_->graphics_queue_family_index;
const uint32_t present_queue_family_index = vk_ctx_->present_queue_family_index;
// For multi threaded applications, we should create a command pool
// for each thread. For this example, we just need one as we go
// with async single core app.
command_pool_ =
space::core::CreateCommandPool(vk_ctx_->device, graphics_queue_family_index);
graphics_queue_ = device->getQueue(graphics_queue_family_index, 0);
present_queue_ = device->getQueue(present_queue_family_index, 0);
descriptor_set_layout_ =
space::core::CreateDescriptorSetLayout(
device, { {vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex} });
pipeline_layout_ =
device->createPipelineLayoutUnique(
vk::PipelineLayoutCreateInfo(
vk::PipelineLayoutCreateFlags(), 1, &descriptor_set_layout_.get()));
pipeline_cache_ =
device->createPipelineCacheUnique(vk::PipelineCacheCreateInfo());
CreateSwapChainContext();
}
void Scene::CreateSwapChainContext() {
vk::PhysicalDevice &physical_device = vk_ctx_->physical_device;
vk::UniqueSurfaceKHR &surface = vk_ctx_->surface;
vk::UniqueDevice &device = vk_ctx_->device;
const uint32_t graphics_queue_family_index = vk_ctx_->graphics_queue_family_index;
const uint32_t present_queue_family_index = vk_ctx_->present_queue_family_index;
const vk::Extent2D extent = QueryExtent();
vk::UniqueCommandBuffer command_buffer =
std::move(
device->allocateCommandBuffersUnique(
vk::CommandBufferAllocateInfo(
*command_pool_, vk::CommandBufferLevel::ePrimary, 1)).front());
// Wait device to be idle before destroying everything
if (swap_chain_context_)
device->waitIdle();
space::core::SwapChainData swap_chain_data(
physical_device, device, *surface, extent,
vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc,
swap_chain_context_ ? std::move(swap_chain_context_->swap_chain_data.swap_chain) : vk::UniqueSwapchainKHR(),
graphics_queue_family_index, present_queue_family_index);
vk::SampleCountFlagBits msaa = space::core::GetMaxUsableSampleCount(physical_device);
space::core::ImageData color_buffer_data(
physical_device, device, swap_chain_data.color_format, extent, vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eTransientAttachment
| vk::ImageUsageFlagBits::eColorAttachment,
vk::ImageLayout::eUndefined,
vk::MemoryPropertyFlagBits::eDeviceLocal,
vk::ImageAspectFlagBits::eColor,
msaa);
space::core::DepthBufferData depth_buffer_data(
physical_device, device, vk::Format::eD16Unorm,
swap_chain_data.extent, vk::ImageUsageFlagBits::eTransientAttachment, msaa);
vk::UniqueRenderPass render_pass =
space::core::CreateRenderPass(
device, swap_chain_data.color_format, depth_buffer_data.format,
vk::AttachmentLoadOp::eClear, vk::ImageLayout::ePresentSrcKHR,
msaa);
std::vector<vk::UniqueFramebuffer> framebuffers =
space::core::CreateFramebuffers(
device, render_pass, swap_chain_data.image_views,
depth_buffer_data.image_view, color_buffer_data.image_view, swap_chain_data.extent);
space::core::BufferData uniform_buffer_data(
physical_device, device, sizeof(glm::mat4x4),
vk::BufferUsageFlagBits::eUniformBuffer);
vk::UniqueDescriptorPool descriptor_pool =
space::core::CreateDescriptorPool(device, { {vk::DescriptorType::eUniformBuffer, 1} });
vk::UniqueDescriptorSet descriptor_set =
std::move(
device->allocateDescriptorSetsUnique(
vk::DescriptorSetAllocateInfo(*descriptor_pool, 1, &*descriptor_set_layout_)).front());
space::core::UpdateDescriptorSets(
device, descriptor_set,
{{vk::DescriptorType::eUniformBuffer, uniform_buffer_data.buffer, vk::UniqueBufferView()}});
struct SwapChainContext *swap_chain_context = new SwapChainContext{
std::move(command_buffer), std::move(swap_chain_data), msaa, std::move(color_buffer_data),
std::move(depth_buffer_data), std::move(uniform_buffer_data),
std::move(render_pass), std::move(framebuffers),
std::move(descriptor_pool), std::move(descriptor_set)};
swap_chain_context_.reset(swap_chain_context);
for (const auto entity : entities_) {
entity->Register(vk_ctx_, &pipeline_layout_, &swap_chain_context_->render_pass,
swap_chain_context_->max_sampling, &pipeline_cache_);
}
}
void Scene::AddEntity(space::Entity *entity) {
// Initialize entity
entity->Register(vk_ctx_, &pipeline_layout_, &swap_chain_context_->render_pass,
swap_chain_context_->max_sampling, &pipeline_cache_);
entities_.push_back(entity);
}
void Scene::SubmitRendering() {
const vk::UniqueDevice &device = vk_ctx_->device;
const space::core::SwapChainData &swap_chain_data = swap_chain_context_->swap_chain_data;
const vk::Queue &graphics_queue = graphics_queue_;
const vk::UniqueCommandBuffer &command_buffer = swap_chain_context_->command_buffer;
const vk::UniqueRenderPass &render_pass = swap_chain_context_->render_pass;
const std::vector<vk::UniqueFramebuffer> &framebuffers = swap_chain_context_->framebuffers;
const vk::UniquePipelineLayout &pipeline_layout = pipeline_layout_;
const vk::UniqueDescriptorSet &descriptor_set = swap_chain_context_->descriptor_set;
const space::core::BufferData &uniform_buffer_data = swap_chain_context_->uniform_buffer_data;
vk::Extent2D extent = swap_chain_context_->swap_chain_data.extent;
const auto aspect_ratio =
static_cast<float>(extent.width) / static_cast<float>(extent.height);
// Update the projection matrices with the current values of camera, model, fov, etc..
auto projection_matrices = camera_->GetProjectionMatrices(aspect_ratio);
// Update uniform buffer
space::core::CopyToDevice(
device, uniform_buffer_data.deviceMemory, projection_matrices.clip
* projection_matrices.projection * projection_matrices.view * projection_matrices.model);
// Get the index of the next available swapchain image:
vk::UniqueSemaphore imageAcquiredSemaphore = device->createSemaphoreUnique(vk::SemaphoreCreateInfo());
bool out_of_date = false;
try {
vk::ResultValue<uint32_t> res =
device->acquireNextImageKHR(
swap_chain_data.swap_chain.get(), FENCE_TIMEOUT,
imageAcquiredSemaphore.get(), nullptr);
if (res.result == vk::Result::eSuboptimalKHR)
out_of_date = true;
assert(res.value < swap_chain_context_->framebuffers.size());
current_buffer_ = res.value;
} catch (vk::OutOfDateKHRError &) {
out_of_date = true;
}
if (out_of_date) {
// Re-create the swapchain context.
CreateSwapChainContext();
// Re-submit rendering
return SubmitRendering();
}
command_buffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlags()));
vk::ClearValue clear_values[3];
clear_values[0].color =
vk::ClearColorValue(std::array<float, 4>({ 0.9f, 0.9f, 0.9f, 1.0f }));
clear_values[1].color =
vk::ClearColorValue(std::array<float, 4>({ 0.9f, 0.9f, 0.9f, 1.0f }));
clear_values[2].depthStencil =
vk::ClearDepthStencilValue(1.0f, 0);
vk::RenderPassBeginInfo renderPassBeginInfo(
render_pass.get(), framebuffers[current_buffer_].get(),
vk::Rect2D(vk::Offset2D(0, 0), swap_chain_data.extent), 3, clear_values);
command_buffer->beginRenderPass(
renderPassBeginInfo, vk::SubpassContents::eInline);
command_buffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, pipeline_layout.get(), 0, descriptor_set.get(), nullptr);
command_buffer->setViewport(
0, vk::Viewport(
0.0f, 0.0f,
static_cast<float>(swap_chain_data.extent.width),
static_cast<float>(swap_chain_data.extent.height), 0.0f, 1.0f));
command_buffer->setScissor(
0, vk::Rect2D(vk::Offset2D(0, 0), swap_chain_data.extent));
for (const auto entity : entities_) {
entity->Draw(&command_buffer);
}
command_buffer->endRenderPass();
command_buffer->end();
device->resetFences(1, &draw_fence_.get());
vk::PipelineStageFlags waitDestinationStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput);
vk::SubmitInfo submitInfo(1, &imageAcquiredSemaphore.get(), &waitDestinationStageMask, 1, &command_buffer.get());
graphics_queue.submit(submitInfo, draw_fence_.get());
}
void Scene::Present() {
vk::UniqueDevice &device = vk_ctx_->device;
space::core::SwapChainData &swap_chain_data = swap_chain_context_->swap_chain_data;
vk::Queue &present_queue = present_queue_;
while (vk::Result::eTimeout
== device->waitForFences(draw_fence_.get(), VK_TRUE, FENCE_TIMEOUT)) { usleep(1000); }
try {
auto result = present_queue.presentKHR(
vk::PresentInfoKHR(0, nullptr, 1, &swap_chain_data.swap_chain.get(), ¤t_buffer_));
assert(result == vk::Result::eSuccess);
} catch (vk::OutOfDateKHRError &) {
// Re-create the swapchain context.
CreateSwapChainContext();
}
}