summaryrefslogtreecommitdiff
path: root/src/vk/device.cpp
blob: ea943c4ba4635e8caf0eb84a50fd433069636179 (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
/*
 * Copyright 2022 Frederico de Oliveira Linhares
 *
 * 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 "device.hpp"

#include <fstream>
#include <new>
#include <vector>
#ifdef DEBUG
#include <sstream>
#endif

#include "../core.hpp"

namespace
{
VkShaderModule
create_shader_module(VkDevice vk_device, const char *filename)
{
  std::ifstream file(filename, std::ios::ate | std::ios::binary);

  if (!file.is_open())
  {
    throw std::runtime_error("Failed to open shader module file.");
  }

  size_t file_size = (size_t) file.tellg();
  std::vector<char> code(file_size);

  file.seekg(0);
  file.read(code.data(), file_size);

  file.close();

  VkShaderModuleCreateInfo create_info = {};
  create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  create_info.codeSize = code.size();
  create_info.pCode = reinterpret_cast<const uint32_t*>(code.data());

  VkShaderModule shader_module;
  if (vkCreateShaderModule(vk_device, &create_info, nullptr,
			   &shader_module) != VK_SUCCESS)
  {
    throw std::runtime_error("Failed to create shader module.");
  }

  return shader_module;
}
}

namespace VK
{

Device::Device(VkPhysicalDevice vk_physical_device, bool with_swapchain)
{
  this->physical_device = vk_physical_device;

  std::vector<VkQueueFamilyProperties> queue_family_properties;

  // Get queue families.
  {
    vkGetPhysicalDeviceQueueFamilyProperties(
      vk_physical_device, &this->queue_families_count, nullptr);
    queue_family_properties.resize(this->queue_families_count);
    vkGetPhysicalDeviceQueueFamilyProperties(
      vk_physical_device, &this->queue_families_count,
      queue_family_properties.data());
  }

  // Get information from physical device.
  {
    VkPhysicalDeviceProperties physical_properties = {};
    vkGetPhysicalDeviceProperties(vk_physical_device, &physical_properties);
    VkPhysicalDeviceFeatures supported_features = {};
    vkGetPhysicalDeviceFeatures(vk_physical_device, &supported_features);

#ifdef DEBUG
    std::stringstream message{};
    message << "Name: " << physical_properties.deviceName << std::endl;
    message << "API version: " << physical_properties.apiVersion <<
      std::endl;
    message << "Driver version: " << physical_properties.driverVersion <<
      std::endl;
    message << "Vendor ID: " << physical_properties.vendorID << std::endl;
    message << "Device ID: " << physical_properties.deviceID << std::endl;
    message << "Device type: " << physical_properties.deviceType <<
      std::endl;
    cg_core.log.message(Log::Level::Trace, message.str());
#endif

    std::vector<VkDeviceQueueCreateInfo> device_queue_create_infos;
    std::vector<std::vector<float>> queue_priorities(
      queue_family_properties.size());
    device_queue_create_infos.resize(queue_family_properties.size());
    for(auto i{0}; i < queue_family_properties.size(); i++)
    {
      // Give different priorities to queues.
      int queue_count = queue_family_properties[i].queueCount;
      queue_priorities[i].resize(queue_count);
      float priority_unity = 1.0f/queue_count;
      for(auto ii{0}; ii < queue_count; ii++)
	queue_priorities[i][ii] = priority_unity * (queue_count - ii);

      device_queue_create_infos[i].sType =
	VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
      device_queue_create_infos[i].pNext = nullptr;
      device_queue_create_infos[i].flags = 0;
      device_queue_create_infos[i].queueFamilyIndex = i;
      device_queue_create_infos[i].queueCount = queue_priorities[i].size();
      device_queue_create_infos[i].pQueuePriorities =
	queue_priorities[i].data();
    }

    VkPhysicalDeviceFeatures required_features = {};
    required_features.multiDrawIndirect = supported_features.multiDrawIndirect;
    required_features.fillModeNonSolid = VK_TRUE;
    required_features.geometryShader = VK_TRUE;
    required_features.tessellationShader = VK_TRUE;
    required_features.samplerAnisotropy = VK_TRUE;

    std::vector<const char*> device_extensions;
    if(with_swapchain)
      device_extensions.emplace_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);

    VkDeviceCreateInfo device_create_info = {};
    device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
    device_create_info.pNext = nullptr;
    device_create_info.flags = 0;
    device_create_info.queueCreateInfoCount = device_queue_create_infos.size();
    device_create_info.pQueueCreateInfos = device_queue_create_infos.data();
    device_create_info.enabledLayerCount = 0;
    device_create_info.ppEnabledLayerNames = nullptr;
    device_create_info.enabledExtensionCount = device_extensions.size();
    if(device_extensions.size() == 0)
      device_create_info.ppEnabledExtensionNames = nullptr;
    else
      device_create_info.ppEnabledExtensionNames = device_extensions.data();

    device_create_info.pEnabledFeatures = &required_features;

    if(vkCreateDevice(this->physical_device, &device_create_info, nullptr,
		      &this->device) != VK_SUCCESS)
      throw std::runtime_error("Failed to create Vulkan physical device.");
  }

  // Load Shaders
  {
    this->vert3d_shader_module = create_shader_module(
      this->device, DATA_DIR "/glsl/shader_3d.vert.spv");
    this->frag3d_shader_module = create_shader_module(
      this->device, DATA_DIR "/glsl/shader_3d.frag.spv");
    this->vert2d_solid_shader_module = create_shader_module(
      this->device, DATA_DIR "/glsl/shader_2d_solid.vert.spv");
    this->frag2d_solid_shader_module = create_shader_module(
      this->device, DATA_DIR "/glsl/shader_2d_solid.frag.spv");
    this->vert2d_wired_shader_module = create_shader_module(
      this->device, DATA_DIR "/glsl/shader_2d_wired.vert.spv");
    this->frag2d_wired_shader_module = create_shader_module(
      this->device, DATA_DIR "/glsl/shader_2d_wired.frag.spv");
  }

  this->queue_families = static_cast<QueueFamily*>(
    std::malloc(this->queue_families_count * sizeof(QueueFamily)));
  for(auto i{0}; i < this->queue_families_count; i++)
  {
    new(&this->queue_families[i])QueueFamily(
      this, i, queue_family_properties[i]);

    // Select families with graphics support.
    auto &family_properties = this->queue_families[i].family_properties;
    if(family_properties.queueCount > 0 &&
       family_properties.queueFlags & VK_QUEUE_GRAPHICS_BIT)
      this->queue_families_with_graphics.push_back(
	&this->queue_families[i]);

    // Select families with presentation support.
    VkBool32 present_supported;
    vkGetPhysicalDeviceSurfaceSupportKHR(
      vk_physical_device, i, cg_core.window_surface, &present_supported);
    if(present_supported)
      this->queue_families_with_presentation.push_back(
	&this->queue_families[i]);
  }
}

Device::~Device()
{
  for(auto i{0}; i < this->queue_families_count; i++)
    this->queue_families[i].~QueueFamily();
  std::free(this->queue_families);

  // Destroy shaders
  vkDestroyShaderModule(this->device, this->vert3d_shader_module, nullptr);
  vkDestroyShaderModule(this->device, this->frag3d_shader_module, nullptr);
  vkDestroyShaderModule(
    this->device, this->vert2d_solid_shader_module, nullptr);
  vkDestroyShaderModule(
    this->device, this->frag2d_solid_shader_module, nullptr);
  vkDestroyShaderModule(
    this->device, this->vert2d_wired_shader_module, nullptr);
  vkDestroyShaderModule(
    this->device, this->frag2d_wired_shader_module, nullptr);

  vkDeviceWaitIdle(this->device);
  vkDestroyDevice(this->device, nullptr);
}

bool
Device::select_memory_type(
  uint32_t *memory_type_index, VkMemoryRequirements *vk_memory_requirements,
  VkMemoryPropertyFlags vk_property_flags)
{
  VkPhysicalDeviceMemoryProperties vk_memory_properties;
  vkGetPhysicalDeviceMemoryProperties(
    this->physical_device, &vk_memory_properties);

  for (auto i{0}; i < vk_memory_properties.memoryTypeCount; i++)
  {
    if(vk_memory_requirements->memoryTypeBits & (1 << i))
    {
      const VkMemoryType& type = vk_memory_properties.memoryTypes[i];

      if ((type.propertyFlags & vk_property_flags) == vk_property_flags)
      {
	*memory_type_index = i;
	return true;
      }
    }
  }

  return false;
}

QueueFamily*
Device::get_queue_family_with_graphics() const
{
  /*
    Returns a random queue family, so not all commands in the engine use the
    same queue.
    TODO: There must be a better way of doing this.
  */
  std::uniform_int_distribution<std::size_t> random_distribution{
    0, this->queue_families_with_graphics.size() -1};
  auto random = random_distribution(random_number_generator);
  return this->queue_families_with_graphics[0];
}

QueueFamily*
Device::get_queue_family_with_presentation() const
{
  /*
    Returns a random queue family, so not all commands in the engine use the
    same queue.
    TODO: There must be a better way of doing this.
  */
  std::uniform_int_distribution<std::size_t> random_distribution{
    0, this->queue_families_with_presentation.size() -1};
  auto random = random_distribution(random_number_generator);
  return this->queue_families_with_presentation[0];
}

}