context.cpp 18.5 KB
Newer Older
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
#include <sf2/sf2.hpp>		// has to be first so he sf2_struct define is set
#include <SDL_vulkan.h>		// has to be includes before vulkan

#include <mirrage/graphic/context.hpp>
#include <mirrage/graphic/device.hpp>
#include <mirrage/graphic/window.hpp>

#include <mirrage/asset/asset_manager.hpp>
#include <mirrage/utils/log.hpp>
#include <mirrage/utils/template_utils.hpp>

#include <SDL2/SDL.h>
#include <gsl/gsl>

#include <iostream>
#include <sstream>
#include <cstdio>


extern "C" {
	VkResult vkCreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
	                                      const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback) {
		auto func = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
		if (func != nullptr) {
			return func(instance, pCreateInfo, pAllocator, pCallback);
		} else {
			return VK_ERROR_EXTENSION_NOT_PRESENT;
		}
	}

	void vkDestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator) {
		auto func = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
		if (func != nullptr) {
			func(instance, callback, pAllocator);
		}
	}
}

39
namespace mirrage {
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
namespace graphic {

	using namespace util::unit_literals;

	namespace {
		void sdl_error_check() {
			const char *err = SDL_GetError();
			if(*err != '\0') {
				std::string errorStr(err);
				SDL_ClearError();
				FAIL("SDL: "<<errorStr);
			}
		}

		void add_present_extensions(std::vector<const char*>& extensions) {
			auto present_extensions = std::vector<const char*>(4);
			auto present_extensions_size = static_cast<unsigned int>(present_extensions.size());
			if(!SDL_GetVulkanInstanceExtensions(&present_extensions_size, present_extensions.data())) {
				FAIL("Unable to determine present extensions: "<<SDL_GetError());
			}

			if(present_extensions_size>0) {
				extensions.insert(extensions.end(), present_extensions.begin(), present_extensions.begin()+present_extensions_size);
			}
		}

		auto check_extensions(const std::vector<const char*>& required,
		                      const std::vector<const char*>& optional) -> std::vector<const char*> {
			auto extensions = std::vector<const char*>();
			extensions.reserve(required.size() + optional.size());

			auto supported_extensions = vk::enumerateInstanceExtensionProperties();

			auto support_confirmed = std::vector<bool>(required.size());

			for(auto& e : supported_extensions) {
				for(auto i=0u; i<required.size(); i++) {
					if(!strcmp(e.extensionName, required[i])) {
						support_confirmed[i] = true;
						extensions.push_back(required[i]);
						break;
					}
				}

				for(auto i=0u; i<optional.size(); i++) {
					if(!strcmp(e.extensionName, optional[i])) {
						extensions.push_back(optional[i]);
						break;
					}
				}
			}

			bool all_supported = true;
			for(auto i=0u; i<support_confirmed.size(); i++) {
				if(!support_confirmed[i]) {
					WARN("Unsupported extension \""<<required[i]<<"\"!");
					all_supported = false;
				}
			}

			if(!all_supported) {
				FAIL("At least one required extension is not supported (see log for details)!");
			}

			return extensions;
		}

		auto check_layers(const std::vector<const char*>& requested) -> std::vector<const char*> {
			auto validation_layers = std::vector<const char*>();
			validation_layers.reserve(requested.size());

			auto supported_layers = vk::enumerateInstanceLayerProperties();
			for(auto& l : supported_layers) {
				bool layer_requested = false;
				for(auto& req_layer : requested) {
					if(0==strcmp(l.layerName, req_layer)) {
						validation_layers.push_back(req_layer);
						layer_requested = true;
						break;
					}
				}

				if(!layer_requested) {
					DEBUG("Additional validation layer is available, that hasn't been requested: "<<l.layerName);
				}
			}

			if(validation_layers.size() != requested.size()) {
				auto log = util::error (__func__, __FILE__, __LINE__);
				log << "Some requested validation layers are not supported: \n";
				for(auto& l : validation_layers) {
					log << "  - "<<l<<"\n";
				}
				log << std::endl;
			}

			return validation_layers;
		}

		VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
		    VkDebugReportFlagsEXT flags,
		    VkDebugReportObjectTypeEXT objType,
		    uint64_t obj,
		    size_t location,
		    int32_t code,
		    const char* layerPrefix,
		    const char* msg,
		    void* userData) {

			// silences: DescriptorSet 0x3f previously bound as set #1 is incompatible with set
			//             0x1cc99c0 newly bound as set #1 so set #2 and any subsequent sets were
			//             disturbed by newly bound pipelineLayout (0x4f)
			if(objType==VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT)
				return VK_FALSE;


			if(flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
				ERROR("[VK | "<<layerPrefix<<"] "<<msg);
			} else if(flags & VK_DEBUG_REPORT_WARNING_BIT_EXT||
			          flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) {
				WARN("[VK | "<<layerPrefix<<"] "<<msg);
			} else {
				INFO("[VK | "<<layerPrefix<<"] "<<msg);
			}

			return VK_FALSE;
		}
	}


	Context::Context(const std::string& appName, uint32_t appVersion,
	                 const std::string& engineName, uint32_t engineVersion,
	                 bool debug, asset::Asset_manager& assets)
	 : _assets(assets), _name(appName) {

		auto maybe_settings = assets.load_maybe<Graphics_settings>("cfg:graphics"_aid);
		if(maybe_settings.is_nothing()) {
			if(!settings(default_settings())) {
				FAIL("Invalid graphics settings");
			}
		} else {
			_settings = maybe_settings.get_or_throw();
		}

		if(!settings(*_settings)) { //< apply actual size/settings
			FAIL("Couldn't apply graphics settings");
		}

		sdl_error_check();

		auto instanceCreateInfo = vk::InstanceCreateInfo{};
		auto appInfo = vk::ApplicationInfo{appName.c_str(), appVersion,
		               engineName.c_str(),engineVersion,
		               VK_API_VERSION_1_0};

		auto required_extensions = std::vector<const char*> {
				VK_KHR_SURFACE_EXTENSION_NAME
		};
		add_present_extensions(required_extensions);
		auto optional_extensions = std::vector<const char*> {
		};


		if(debug) {
			_enabled_layers = check_layers({
				"VK_LAYER_LUNARG_standard_validation"
			});

			required_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
		}

		auto extensions = check_extensions(required_extensions, optional_extensions);

		auto log = util::info (__func__, __FILE__, __LINE__);
		log << "Initializing vulkan...\n";
		log << "Enabled extensions:\n";
		for(auto e : extensions) {
			log << "  - "<<e<<"\n";
		}
		log << "Enabled validation layers:\n";
		for(auto l : _enabled_layers) {
			log << "  - "<<l<<"\n";
		}
		log << std::endl;

		instanceCreateInfo.setPApplicationInfo(&appInfo);
		instanceCreateInfo.setEnabledExtensionCount(gsl::narrow<uint32_t>(extensions.size()));
		instanceCreateInfo.setPpEnabledExtensionNames(extensions.data());
		instanceCreateInfo.setEnabledLayerCount(gsl::narrow<uint32_t>(_enabled_layers.size()));
		instanceCreateInfo.setPpEnabledLayerNames(_enabled_layers.data());
		_instance = vk::createInstanceUnique(instanceCreateInfo);

		if(debug) {
			_debug_callback = _instance->createDebugReportCallbackEXTUnique({
			/*	vk::DebugReportFlagBitsEXT::eDebug | vk::DebugReportFlagBitsEXT::eInformation | */
				vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::ePerformanceWarning |
				vk::DebugReportFlagBitsEXT::eWarning,
				debugCallback
			});
		}

	}
	Context::~Context() = default;

	bool Context::settings(Graphics_settings new_settings) {
		// TODO: update windows
		/*
		for(auto device : children()) {
			if(!device->settings_changed(new_settings)) {
				WARN("New graphics settings are not supported");
				return false;
			}
		}*/

		_assets.save<Graphics_settings>("cfg:graphics"_aid, new_settings);
		_settings = _assets.load<Graphics_settings>("cfg:graphics"_aid);

		return true;
	}

	auto Context::create_window(std::string name, int width, int height) -> Window_ptr {
		auto settings =_find_window_settings(name, width, height);

		return std::make_unique<Window>(*this, name, app_name() + " | " + name, settings.display,
		                                settings.width, settings.height, settings.fullscreen);
	}
	auto Context::_find_window_settings(const std::string& name,
	                                   int width, int height) -> Window_settings {
		auto& cfg = settings();

		auto win_cfg = std::find_if(std::begin(cfg.windows), std::end(cfg.windows),
		                            [&](auto& w) {return w.first==name;});

		if(win_cfg==std::end(cfg.windows)) { // no config create new
			auto new_settings = cfg;
			auto win_settings = default_window_settings(0);
			if(width>0)  win_settings.width = width;
			if(height>0) win_settings.height = height;
			new_settings.windows[name] = win_settings;

			settings(new_settings);

			return win_settings;
		}

		return win_cfg->second;
	}

	namespace {
		bool supports_present(vk::PhysicalDevice& gpu, const std::vector<Window*>& can_present_to) {
			auto supported_extensions = gpu.enumerateDeviceExtensionProperties();
			auto sc_ext = std::find_if(supported_extensions.begin(), supported_extensions.end(), [](auto& e) {
				return std::strcmp(e.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)==0;
			});

			if(sc_ext==supported_extensions.end()) {
				return false;
			}

			for(auto window : can_present_to) {
				auto formats       = gpu.getSurfaceFormatsKHR(window->surface());
				auto present_modes = gpu.getSurfacePresentModesKHR(window->surface());

				if(formats.empty() || present_modes.empty())
					return false;
			}

			return true;
		}
		
		auto find_graphics_queue(vk::PhysicalDevice& gpu, const std::vector<Window*>& can_present_to) -> util::maybe<std::uint32_t> {
			auto i=0;

			for(auto& queue_family : gpu.getQueueFamilyProperties()) {
				auto can_present = can_present_to.empty() || std::all_of(can_present_to.begin(),
				                                                         can_present_to.end(),
				                                                         [&](auto window) {
					return gpu.getSurfaceSupportKHR(i, window->surface());
				});

				if(queue_family.queueCount>0
				   && can_present
				   && queue_family.timestampValidBits>=32 // only accept queues with >=32bit timer support, for now
				   && (queue_family.queueFlags & vk::QueueFlagBits::eGraphics)) {
					return i;
				}

				i++;
			}

			return util::nothing;
		}

		auto find_transfer_queue(vk::PhysicalDevice& gpu) -> std::uint32_t {
			auto families = gpu.getQueueFamilyProperties();
			
			auto i = 0;
			
			// check for transfer-only queue
			for(auto& queue_family : families) {
				if(queue_family.queueCount>0
				   && (queue_family.queueFlags & vk::QueueFlagBits::eTransfer)
				   && !(queue_family.queueFlags & vk::QueueFlagBits::eGraphics) ) {
					return i;
				}

				i++;
			}
			
			i=0;
			for(auto& queue_family : families) {
				if(queue_family.queueCount>0
				   && ((queue_family.queueFlags & vk::QueueFlagBits::eTransfer)
				      || (queue_family.queueFlags & vk::QueueFlagBits::eGraphics)
				      || (queue_family.queueFlags & vk::QueueFlagBits::eCompute)) ) {
					return i;
				}

				i++;
			}
			
			FAIL("No queue found, that supports transfer operations!");
		}

		auto find_surface_format(vk::PhysicalDevice& gpu, Window& window,
		                         vk::Format target_format, vk::ColorSpaceKHR target_space) -> vk::SurfaceFormatKHR {

			auto formats = gpu.getSurfaceFormatsKHR(window.surface());
			if(formats.size()==1 && formats.front().format==vk::Format::eUndefined) {
				return {target_format, target_space};

			}

			auto opt_found = std::find_if(formats.begin(), formats.end(), [&](auto& f) {
				return f.format==target_format && f.colorSpace==target_space;
			});
			if(opt_found!=formats.end()) {
				return {target_format, target_space};
			}

			opt_found = std::find_if(formats.begin(), formats.end(), [&](auto& f) {
				return f.format==target_format;
			});
			if(opt_found!=formats.end()) {
				return *opt_found;
			}

			if(!formats.empty()) {
				WARN("Requested format is not supported by the device, fallback to first reported format");
				return formats.front();
			} else {
				FAIL("The device doesn't support any surface formats!");
			}
		}

		auto create_swapchain_create_info(vk::PhysicalDevice gpu, bool srgb,
		                                  const std::vector<Window*>& can_present_to) {
			auto swapchains = Swapchain_create_infos();
			
			for(auto window : can_present_to) {
				auto capabilities = gpu.getSurfaceCapabilitiesKHR(window->surface());
	
	
				auto sc_info = vk::SwapchainCreateInfoKHR{};
				sc_info.setSurface(window->surface());
				sc_info.setClipped(true);
				sc_info.setPreTransform(capabilities.currentTransform);
				sc_info.setImageSharingMode(vk::SharingMode::eExclusive);
				sc_info.setImageUsage(vk::ImageUsageFlagBits::eColorAttachment);
				sc_info.setImageArrayLayers(1);
				sc_info.setMinImageCount(std::max(2u, capabilities.minImageCount));
				if(capabilities.maxImageCount>0 && capabilities.maxImageCount<sc_info.minImageCount) {
					sc_info.setMinImageCount(capabilities.maxImageCount);
				}
	
				auto present_modes = gpu.getSurfacePresentModesKHR(window->surface());
				auto mailbox_supported = std::find(present_modes.begin(), present_modes.end(),
				                                   vk::PresentModeKHR::eMailbox)!=present_modes.end();
				if(mailbox_supported) {
					sc_info.setPresentMode(vk::PresentModeKHR::eMailbox);
				} else {
					sc_info.setPresentMode(vk::PresentModeKHR::eFifo);
				}
	
				if(capabilities.currentExtent.width == std::numeric_limits<uint32_t>::max()) {
					capabilities.currentExtent.width = std::min(std::max(gsl::narrow<std::uint32_t>(window->width()),
					                                                     capabilities.minImageExtent.width),
					                                            capabilities.maxImageExtent.width);
	
					capabilities.currentExtent.height = std::min(std::max(gsl::narrow<std::uint32_t>(window->height()),
					                                                      capabilities.minImageExtent.height),
					                                             capabilities.maxImageExtent.height);
				}
	
				sc_info.setImageExtent(capabilities.currentExtent);
	
				auto format = find_surface_format(gpu, *window, srgb ? vk::Format::eB8G8R8A8Srgb
				                                                     : vk::Format::eB8G8R8A8Unorm,
				                                  vk::ColorSpaceKHR::eSrgbNonlinear);
	
				sc_info.setImageFormat(format.format);
				sc_info.setImageColorSpace(format.colorSpace);
	
				swapchains.emplace(window->name(), std::make_tuple(window, sc_info));
			}
			
			return swapchains;
		}
	}
	auto Context::instantiate_device(Device_selector selector, Device_factory factory,
	                                 const std::vector<Window*>& can_present_to, bool srgb) -> Device_ptr {
		auto top_score = std::numeric_limits<int>::min();
		auto top_gpu   = vk::PhysicalDevice{};

		for(auto& gpu : _instance->enumeratePhysicalDevices()) {
			if(!can_present_to.empty() && !supports_present(gpu, can_present_to)) {
				continue;
			}
			
			auto graphics_queue = find_graphics_queue(gpu, can_present_to);

			auto score = selector(gpu, graphics_queue);
			if(score>top_score) {
				top_score = score;
				top_gpu = gpu;
			}
		}

		if(!top_gpu) {
			FAIL("Couldn't find a GPU that supports vulkan and all required features.");
		}

		auto cfg = vk::DeviceCreateInfo{};
		cfg.setEnabledLayerCount(gsl::narrow<uint32_t>(_enabled_layers.size()));
		cfg.setPpEnabledLayerNames(_enabled_layers.data());

		auto extensions = std::vector<const char*>();
		auto supported_extensions = top_gpu.enumerateDeviceExtensionProperties();
		auto extension_supported = [&](const char* e) {
			return supported_extensions.end() != std::find_if(supported_extensions.begin(),
			                                                  supported_extensions.end(),
			                                                  [&](auto& se) {
				return !strcmp(se.extensionName, e);
			});
		};
		
		auto dedicated_alloc_supported = false;
		
#ifdef VK_NV_dedicated_allocation
		if(extension_supported(VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME)) {
			extensions.emplace_back(VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME);
			dedicated_alloc_supported = true;
		}
#endif
		
		if(!can_present_to.empty()) {
			extensions.emplace_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
		}
		
		cfg.setEnabledExtensionCount(extensions.size());
		cfg.setPpEnabledExtensionNames(extensions.data());
		
		auto create_info = factory(top_gpu, find_graphics_queue(top_gpu, can_present_to));

		cfg.setPEnabledFeatures(&create_info.features);
		
		// familyId => (count, priorities)
		auto queue_families = std::unordered_map<std::uint32_t,
		                                         std::tuple<std::uint32_t,std::vector<float>>>();
		
		auto available_families = top_gpu.getQueueFamilyProperties();
		
		auto queue_mapping = Queue_family_mapping();

		auto transfer_queue_tag = "_transfer"_strid;
		create_info.queue_families.emplace(transfer_queue_tag, Queue_create_info{find_transfer_queue(top_gpu), 0.2f});

		for(auto& qf : create_info.queue_families) {
			auto tag = qf.first;
			auto family = qf.second.family_id;
			auto priority = qf.second.priority;
			
			auto& entry = queue_families[family];
			
			if(available_families[family].queueCount > 0) {
				available_families[family].queueCount--;
				std::get<0>(entry) += 1;
				std::get<1>(entry).emplace_back(priority);
			} else {
				WARN("More queues requested than are availbalbe from family "<<family<<". Collapsed with previous queue!");
			}

			queue_mapping.emplace(tag, std::make_tuple(family, std::get<1>(entry).size()-1));
		}

		auto used_queues = std::vector<vk::DeviceQueueCreateInfo>{};
		used_queues.reserve(queue_families.size());
		for(auto& qf : queue_families) {
			INVARIANT(std::get<1>(qf.second).size()==std::get<0>(qf.second),
			          "Size mismatch");
			
			used_queues.emplace_back(vk::DeviceQueueCreateFlags(),
			                         qf.first,
			                         std::get<0>(qf.second),
			                         std::get<1>(qf.second).data());
		}
		
		cfg.setQueueCreateInfoCount(gsl::narrow<std::uint32_t>(used_queues.size()));
		cfg.setPQueueCreateInfos(used_queues.data());
		
		auto swapchains = create_swapchain_create_info(top_gpu, srgb, can_present_to);
		
		return std::make_unique<Device>(*this, _assets, top_gpu.createDeviceUnique(cfg), top_gpu,
		                                transfer_queue_tag, std::move(queue_mapping),
		                                std::move(swapchains), dedicated_alloc_supported );
	}

}
}