aboutsummaryrefslogtreecommitdiff
path: root/src/vulkan/engine_vulkan.cc
blob: 451aa3f8d9d7ebb7fa874c6ae4fc17869423c752 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// Copyright 2018 The Amber Authors.
//
// 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.

#include "src/vulkan/engine_vulkan.h"

#include <algorithm>
#include <cassert>

#include "amber/amber_vulkan.h"
#include "src/make_unique.h"
#include "src/vulkan/compute_pipeline.h"
#include "src/vulkan/descriptor.h"
#include "src/vulkan/format_data.h"
#include "src/vulkan/graphics_pipeline.h"

namespace amber {
namespace vulkan {
namespace {

const uint32_t kFramebufferWidth = 250;
const uint32_t kFramebufferHeight = 250;

VkShaderStageFlagBits ToVkShaderStage(ShaderType type) {
  switch (type) {
    case kShaderTypeGeometry:
      return VK_SHADER_STAGE_GEOMETRY_BIT;
    case kShaderTypeFragment:
      return VK_SHADER_STAGE_FRAGMENT_BIT;
    case kShaderTypeVertex:
      return VK_SHADER_STAGE_VERTEX_BIT;
    case kShaderTypeTessellationControl:
      return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
    case kShaderTypeTessellationEvaluation:
      return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
    case kShaderTypeCompute:
      return VK_SHADER_STAGE_COMPUTE_BIT;
  }

  assert(false && "Vulkan::Unknown shader stage");
  return VK_SHADER_STAGE_FRAGMENT_BIT;
}

}  // namespace

EngineVulkan::EngineVulkan() : Engine() {}

EngineVulkan::~EngineVulkan() = default;

Result EngineVulkan::Initialize(EngineConfig* config,
                                const std::vector<Feature>& features,
                                const std::vector<std::string>& extensions) {
  if (device_)
    return Result("Vulkan::Initialize device_ already exists");

  VulkanEngineConfig* vk_config = static_cast<VulkanEngineConfig*>(config);
  if (!vk_config || vk_config->vkGetInstanceProcAddr == VK_NULL_HANDLE)
    return Result("Vulkan::Initialize vkGetInstanceProcAddr must be provided.");

  // If the device is provided, the physical_device and queue are also required.
  if (vk_config->device != VK_NULL_HANDLE) {
    if (vk_config->physical_device == VK_NULL_HANDLE)
      return Result("Vulkan::Initialize physical device handle is null.");
    if (vk_config->queue == VK_NULL_HANDLE)
      return Result("Vulkan::Initialize queue handle is null.");

    device_ = MakeUnique<Device>(
        vk_config->instance, vk_config->physical_device,
        vk_config->available_features, vk_config->available_extensions,
        vk_config->queue_family_index, vk_config->device, vk_config->queue);
  } else {
    device_ = MakeUnique<Device>();
  }

  Result r = device_->Initialize(vk_config->vkGetInstanceProcAddr, features,
                                 extensions);
  if (!r.IsSuccess())
    return r;

  if (!pool_) {
    pool_ = MakeUnique<CommandPool>(device_.get());
    r = pool_->Initialize(device_->GetQueueFamilyIndex());
    if (!r.IsSuccess())
      return r;
  }

  // Set VK_FORMAT_B8G8R8A8_UNORM for color frame buffer in default.
  color_frame_format_ = MakeUnique<Format>();
  color_frame_format_->SetFormatType(FormatType::kB8G8R8A8_UNORM);
  color_frame_format_->AddComponent(FormatComponentType::kB, FormatMode::kUNorm,
                                    8);
  color_frame_format_->AddComponent(FormatComponentType::kG, FormatMode::kUNorm,
                                    8);
  color_frame_format_->AddComponent(FormatComponentType::kR, FormatMode::kUNorm,
                                    8);
  color_frame_format_->AddComponent(FormatComponentType::kA, FormatMode::kUNorm,
                                    8);

  // Set VK_FORMAT_UNDEFINED for depth/stencil frame buffer in default.
  depth_frame_format_ = MakeUnique<Format>();
  depth_frame_format_->SetFormatType(FormatType::kUnknown);

  return {};
}

Result EngineVulkan::Shutdown() {
  if (!device_)
    return {};

  for (auto it = modules_.begin(); it != modules_.end(); ++it) {
    auto vk_device = device_->GetDevice();
    if (vk_device != VK_NULL_HANDLE && it->second != VK_NULL_HANDLE)
      device_->GetPtrs()->vkDestroyShaderModule(vk_device, it->second, nullptr);
  }

  if (pipeline_)
    pipeline_->Shutdown();

  if (vertex_buffer_)
    vertex_buffer_->Shutdown();

  if (pool_)
    pool_->Shutdown();

  device_->Shutdown();
  return {};
}

Result EngineVulkan::CreatePipeline(PipelineType type) {
  const auto& engine_data = GetEngineData();

  if (type == PipelineType::kCompute) {
    pipeline_ = MakeUnique<ComputePipeline>(
        device_.get(), device_->GetPhysicalDeviceProperties(),
        device_->GetPhysicalMemoryProperties(), engine_data.fence_timeout_ms,
        GetShaderStageInfo());
    return pipeline_->AsCompute()->Initialize(pool_->GetCommandPool(),
                                              device_->GetQueue());
  }

  pipeline_ = MakeUnique<GraphicsPipeline>(
      device_.get(), device_->GetPhysicalDeviceProperties(),
      device_->GetPhysicalMemoryProperties(),
      ToVkFormat(color_frame_format_->GetFormatType()),
      ToVkFormat(depth_frame_format_->GetFormatType()),
      engine_data.fence_timeout_ms, GetShaderStageInfo());

  return pipeline_->AsGraphics()->Initialize(
      kFramebufferWidth, kFramebufferHeight, pool_->GetCommandPool(),
      device_->GetQueue());
}

Result EngineVulkan::SetShader(ShaderType type,
                               const std::vector<uint32_t>& data) {
  VkShaderModuleCreateInfo info = VkShaderModuleCreateInfo();
  info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  info.codeSize = data.size() * sizeof(uint32_t);
  info.pCode = data.data();

  auto it = modules_.find(type);
  if (it != modules_.end())
    return Result("Vulkan::Setting Duplicated Shader Types Fail");

  VkShaderModule shader;
  if (device_->GetPtrs()->vkCreateShaderModule(
          device_->GetDevice(), &info, nullptr, &shader) != VK_SUCCESS) {
    return Result("Vulkan::Calling vkCreateShaderModule Fail");
  }

  modules_[type] = shader;
  return {};
}

std::vector<VkPipelineShaderStageCreateInfo>
EngineVulkan::GetShaderStageInfo() {
  std::vector<VkPipelineShaderStageCreateInfo> stage_info(modules_.size());
  uint32_t stage_count = 0;
  for (auto it : modules_) {
    stage_info[stage_count] = VkPipelineShaderStageCreateInfo();
    stage_info[stage_count].sType =
        VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    stage_info[stage_count].stage = ToVkShaderStage(it.first);
    stage_info[stage_count].module = it.second;
    stage_info[stage_count].pName = nullptr;
    ++stage_count;
  }
  return stage_info;
}

Result EngineVulkan::SetBuffer(BufferType type,
                               uint8_t location,
                               const Format& format,
                               const std::vector<Value>& values) {
  auto format_type = ToVkFormat(format.GetFormatType());
  if (type != BufferType::kIndex &&
      !IsFormatSupportedByPhysicalDevice(type, device_->GetPhysicalDevice(),
                                         format_type)) {
    return Result("Vulkan::SetBuffer format is not supported for buffer type");
  }

  // Handle image and depth attachments special as they come in before
  // the pipeline is created.
  if (type == BufferType::kColor) {
    *color_frame_format_ = format;
    return {};
  }
  if (type == BufferType::kDepth) {
    *depth_frame_format_ = format;
    return {};
  }

  if (!pipeline_)
    return Result("Vulkan::SetBuffer no Pipeline exists");

  if (!pipeline_->IsGraphics())
    return Result("Vulkan::SetBuffer for Non-Graphics Pipeline");

  if (type == BufferType::kVertex) {
    if (!vertex_buffer_)
      vertex_buffer_ = MakeUnique<VertexBuffer>(device_.get());

    pipeline_->AsGraphics()->SetVertexBuffer(location, format, values,
                                             vertex_buffer_.get());
    return {};
  }

  if (type == BufferType::kIndex) {
    pipeline_->AsGraphics()->SetIndexBuffer(values);
    return {};
  }

  return Result("Vulkan::SetBuffer unknown buffer type");
}

Result EngineVulkan::DoClearColor(const ClearColorCommand* command) {
  if (!pipeline_->IsGraphics())
    return Result("Vulkan::Clear Color Command for Non-Graphics Pipeline");

  return pipeline_->AsGraphics()->SetClearColor(
      command->GetR(), command->GetG(), command->GetB(), command->GetA());
}

Result EngineVulkan::DoClearStencil(const ClearStencilCommand* command) {
  if (!pipeline_->IsGraphics())
    return Result("Vulkan::Clear Stencil Command for Non-Graphics Pipeline");

  return pipeline_->AsGraphics()->SetClearStencil(command->GetValue());
}

Result EngineVulkan::DoClearDepth(const ClearDepthCommand* command) {
  if (!pipeline_->IsGraphics())
    return Result("Vulkan::Clear Depth Command for Non-Graphics Pipeline");

  return pipeline_->AsGraphics()->SetClearDepth(command->GetValue());
}

Result EngineVulkan::DoClear(const ClearCommand*) {
  if (!pipeline_->IsGraphics())
    return Result("Vulkan::Clear Command for Non-Graphics Pipeline");

  return pipeline_->AsGraphics()->Clear();
}

Result EngineVulkan::DoDrawRect(const DrawRectCommand* command) {
  if (!pipeline_->IsGraphics())
    return Result("Vulkan::DrawRect for Non-Graphics Pipeline");

  auto* graphics = pipeline_->AsGraphics();

  Result r = graphics->ResetPipeline();
  if (!r.IsSuccess())
    return r;

  // |format| is not Format for frame buffer but for vertex buffer.
  // Since draw rect command contains its vertex information and it
  // does not include a format of vertex buffer, we can choose any
  // one that is suitable. We use VK_FORMAT_R32G32_SFLOAT for it.
  Format format;
  format.SetFormatType(FormatType::kR32G32_SFLOAT);
  format.AddComponent(FormatComponentType::kR, FormatMode::kSFloat, 32);
  format.AddComponent(FormatComponentType::kG, FormatMode::kSFloat, 32);

  float x = command->GetX();
  float y = command->GetY();
  float width = command->GetWidth();
  float height = command->GetHeight();
  if (command->IsOrtho()) {
    const float frame_width = static_cast<float>(graphics->GetWidth());
    const float frame_height = static_cast<float>(graphics->GetHeight());
    x = ((x / frame_width) * 2.0f) - 1.0f;
    y = ((y / frame_height) * 2.0f) - 1.0f;
    width = ((width / frame_width) * 2.0f) - 1.0f;
    height = ((height / frame_height) * 2.0f) - 1.0f;
  }

  std::vector<Value> values(8);
  // Bottom left
  values[0].SetDoubleValue(static_cast<double>(x));
  values[1].SetDoubleValue(static_cast<double>(y + height));
  // Top left
  values[2].SetDoubleValue(static_cast<double>(x));
  values[3].SetDoubleValue(static_cast<double>(y));
  // Bottom right
  values[4].SetDoubleValue(static_cast<double>(x + width));
  values[5].SetDoubleValue(static_cast<double>(y + height));
  // Top right
  values[6].SetDoubleValue(static_cast<double>(x + width));
  values[7].SetDoubleValue(static_cast<double>(y));

  auto vertex_buffer = MakeUnique<VertexBuffer>(device_.get());

  r = graphics->SetVertexBuffer(0, format, values, vertex_buffer.get());
  if (!r.IsSuccess())
    return r;

  PipelineData data;
  DrawArraysCommand draw(data);
  draw.SetTopology(command->IsPatch() ? Topology::kPatchList
                                      : Topology::kTriangleStrip);
  draw.SetFirstVertexIndex(0);
  draw.SetVertexCount(4);
  draw.SetInstanceCount(1);

  r = graphics->Draw(&draw, vertex_buffer.get());
  if (!r.IsSuccess())
    return r;

  r = graphics->ResetPipeline();
  if (!r.IsSuccess())
    return r;

  vertex_buffer->Shutdown();
  return {};
}

Result EngineVulkan::DoDrawArrays(const DrawArraysCommand* command) {
  if (!pipeline_->IsGraphics())
    return Result("Vulkan::DrawArrays for Non-Graphics Pipeline");

  return pipeline_->AsGraphics()->Draw(command, vertex_buffer_.get());
}

Result EngineVulkan::DoCompute(const ComputeCommand* command) {
  if (pipeline_->IsGraphics())
    return Result("Vulkan: Compute called for graphics pipeline.");

  return pipeline_->AsCompute()->Compute(command->GetX(), command->GetY(),
                                         command->GetZ());
}

Result EngineVulkan::DoEntryPoint(const EntryPointCommand* command) {
  if (!pipeline_)
    return Result("Vulkan::DoEntryPoint no Pipeline exists");

  pipeline_->SetEntryPointName(ToVkShaderStage(command->GetShaderType()),
                               command->GetEntryPointName());
  return {};
}

Result EngineVulkan::DoPatchParameterVertices(
    const PatchParameterVerticesCommand*) {
  return Result("Vulkan::DoPatch Not Implemented");
}

Result EngineVulkan::DoProcessCommands() {
  return pipeline_->ProcessCommands();
}

Result EngineVulkan::GetFrameBufferInfo(ResourceInfo* info) {
  assert(info);

  if (!pipeline_->IsGraphics())
    return Result("Vulkan::GetFrameBufferInfo for Non-Graphics Pipeline");

  const auto graphics = pipeline_->AsGraphics();
  const auto frame = graphics->GetFrame();
  const auto bytes_per_texel = color_frame_format_->GetByteSize();
  info->type = ResourceInfoType::kImage;
  info->image_info.width = frame->GetWidth();
  info->image_info.height = frame->GetHeight();
  info->image_info.depth = 1U;
  info->image_info.texel_stride = bytes_per_texel;
  info->image_info.texel_format = color_frame_format_.get();
  // When copying the image to the host buffer, we specify a row length of 0
  // which results in tight packing of rows.  So the row stride is the product
  // of the texel stride and the number of texels in a row.
  const auto row_stride = bytes_per_texel * frame->GetWidth();
  info->image_info.row_stride = row_stride;
  info->size_in_bytes = row_stride * frame->GetHeight();
  info->cpu_memory = frame->GetColorBufferPtr();

  return {};
}

Result EngineVulkan::GetDescriptorInfo(const uint32_t descriptor_set,
                                       const uint32_t binding,
                                       ResourceInfo* info) {
  return pipeline_->GetDescriptorInfo(descriptor_set, binding, info);
}

Result EngineVulkan::DoBuffer(const BufferCommand* command) {
  if (command->IsPushConstant())
    return pipeline_->AddPushConstant(command);

  if (!IsDescriptorSetInBounds(device_->GetPhysicalDevice(),
                               command->GetDescriptorSet())) {
    return Result(
        "Vulkan::DoBuffer exceed maxBoundDescriptorSets limit of physical "
        "device");
  }

  return pipeline_->AddDescriptor(command);
}

bool EngineVulkan::IsFormatSupportedByPhysicalDevice(
    BufferType type,
    VkPhysicalDevice physical_device,
    VkFormat format) {
  VkFormatProperties properties = VkFormatProperties();
  device_->GetPtrs()->vkGetPhysicalDeviceFormatProperties(physical_device,
                                                          format, &properties);

  VkFormatFeatureFlagBits flag = VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT;
  bool is_buffer_type_image = false;
  switch (type) {
    case BufferType::kColor:
      flag = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;
      is_buffer_type_image = true;
      break;
    case BufferType::kDepth:
      flag = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
      is_buffer_type_image = true;
      break;
    case BufferType::kSampled:
      flag = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
      is_buffer_type_image = true;
      break;
    case BufferType::kVertex:
      flag = VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT;
      is_buffer_type_image = false;
      break;
    default:
      return false;
  }

  return ((is_buffer_type_image ? properties.optimalTilingFeatures
                                : properties.bufferFeatures) &
          flag) == flag;
}

bool EngineVulkan::IsDescriptorSetInBounds(VkPhysicalDevice physical_device,
                                           uint32_t descriptor_set) {
  VkPhysicalDeviceProperties properties = VkPhysicalDeviceProperties();
  device_->GetPtrs()->vkGetPhysicalDeviceProperties(physical_device,
                                                    &properties);
  return properties.limits.maxBoundDescriptorSets > descriptor_set;
}

}  // namespace vulkan
}  // namespace amber