forked from SaschaWillems/Vulkan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphicspipelinelibrary.cpp
533 lines (442 loc) · 20.7 KB
/
graphicspipelinelibrary.cpp
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
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
/*
* Vulkan Example - Using VK_EXT_graphics_pipeline_library
*
* Copyright (C) 2022 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include "vulkanexamplebase.h"
#include "VulkanglTFModel.h"
#include <thread>
#include <mutex>
#define ENABLE_VALIDATION false
class VulkanExample: public VulkanExampleBase
{
public:
bool linkTimeOptimization = true;
vkglTF::Model scene;
struct UBOVS {
glm::mat4 projection;
glm::mat4 modelView;
glm::vec4 lightPos = glm::vec4(0.0f, -2.0f, 1.0f, 0.0f);
} uboVS;
vks::Buffer uniformBuffer;
VkPipelineLayout pipelineLayout;
VkDescriptorSet descriptorSet;
VkDescriptorSetLayout descriptorSetLayout;
VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT graphicsPipelineLibraryFeatures{};
struct PipelineLibrary {
VkPipeline vertexInputInterface;
VkPipeline preRasterizationShaders;
VkPipeline fragmentOutputInterface;
std::vector<VkPipeline> fragmentShaders;
} pipelineLibrary;
std::vector<VkPipeline> pipelines{};
struct ShaderInfo {
uint32_t* code;
size_t size;
};
std::mutex mutex;
VkPipelineCache threadPipelineCache{ VK_NULL_HANDLE };
bool newPipelineCreated = false;
uint32_t splitX{ 2 };
uint32_t splitY{ 2 };
std::vector<glm::vec3> colors{};
float rotation{ 0.0f };
VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION)
{
title = "Graphics pipeline library";
camera.type = Camera::CameraType::lookat;
camera.setPosition(glm::vec3(0.0f, 0.0f, -2.0f));
camera.setRotation(glm::vec3(-25.0f, 15.0f, 0.0f));
camera.setRotationSpeed(0.5f);
// Enable required extensions
enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
enabledDeviceExtensions.push_back(VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME);
enabledDeviceExtensions.push_back(VK_EXT_GRAPHICS_PIPELINE_LIBRARY_EXTENSION_NAME);
// Enable required extension features
graphicsPipelineLibraryFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GRAPHICS_PIPELINE_LIBRARY_FEATURES_EXT;
graphicsPipelineLibraryFeatures.graphicsPipelineLibrary = VK_TRUE;
deviceCreatepNextChain = &graphicsPipelineLibraryFeatures;
}
~VulkanExample()
{
if (device) {
for (auto pipeline : pipelines) {
vkDestroyPipeline(device, pipeline, nullptr);
}
for (auto pipeline : pipelineLibrary.fragmentShaders) {
vkDestroyPipeline(device, pipeline, nullptr);
}
vkDestroyPipeline(device, pipelineLibrary.fragmentOutputInterface, nullptr);
vkDestroyPipeline(device, pipelineLibrary.preRasterizationShaders, nullptr);
vkDestroyPipeline(device, pipelineLibrary.vertexInputInterface, nullptr);
vkDestroyPipelineCache(device, threadPipelineCache, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
uniformBuffer.destroy();
}
}
void buildCommandBuffers()
{
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = defaultClearColor;
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = renderPass;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = width;
renderPassBeginInfo.renderArea.extent.height = height;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
for (int32_t i = 0; i < drawCmdBuffers.size(); ++i)
{
renderPassBeginInfo.framebuffer = frameBuffers[i];
VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo));
vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, NULL);
scene.bindBuffers(drawCmdBuffers[i]);
// Render a viewport for each pipeline
float w = (float)width / (float)splitX;
float h = (float)height / (float)splitY;
uint32_t idx = 0;
for (uint32_t y = 0; y < splitX; y++) {
for (uint32_t x = 0; x < splitY; x++) {
VkViewport viewport{};
viewport.x = w * (float)x;
viewport.y = h * (float)y;
viewport.width = w;
viewport.height = h;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport);
VkRect2D scissor{};
scissor.extent.width = (uint32_t)w;
scissor.extent.height = (uint32_t)h;
scissor.offset.x = (uint32_t)w * x;
scissor.offset.y = (uint32_t)h * y;
vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor);
if (pipelines.size() > idx) {
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines[idx]);
scene.draw(drawCmdBuffers[i]);
}
idx++;
}
}
drawUI(drawCmdBuffers[i]);
vkCmdEndRenderPass(drawCmdBuffers[i]);
VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i]));
}
}
void loadAssets()
{
const uint32_t glTFLoadingFlags = vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY;
scene.loadFromFile(getAssetPath() + "models/color_teapot_spheres.gltf", vulkanDevice, queue, glTFLoadingFlags);
}
void setupDescriptorPool()
{
std::vector<VkDescriptorPoolSize> poolSizes = {
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1)
};
VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout()
{
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0)
};
VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout));
}
void setupDescriptorSet()
{
VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
std::vector<VkWriteDescriptorSet> writeDescriptorSets = {
vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffer.descriptor)
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, nullptr);
}
// With VK_EXT_graphics_pipeline_library we don't need to create the shader module when loading it, but instead have the driver create it at linking time
// So we use a custom function that only loads the required shader information without actually creating the shader module
bool loadShaderFile(std::string fileName, ShaderInfo &shaderInfo)
{
#if defined(__ANDROID__)
// Load shader from compressed asset
// @todo
AAsset* asset = AAssetManager_open(androidApp->activity->assetManager, fileName, AASSET_MODE_STREAMING);
assert(asset);
size_t size = AAsset_getLength(asset);
assert(size > 0);
shaderInfo.size = size;
shaderInfo.code = new uint32_t[size / 4];
AAsset_read(asset, shaderCode, size);
AAsset_close(asset);
#else
std::ifstream is(fileName, std::ios::binary | std::ios::in | std::ios::ate);
if (is.is_open())
{
shaderInfo.size = is.tellg();
is.seekg(0, std::ios::beg);
shaderInfo.code = new uint32_t[shaderInfo.size];
is.read(reinterpret_cast<char*>(shaderInfo.code), shaderInfo.size);
is.close();
return true;
} else {
std::cerr << "Error: Could not open shader file \"" << fileName << "\"" << "\n";
throw std::runtime_error("Could open shader file");
return false;
}
#endif
}
// Create the shared pipeline parts up-front
void preparePipelineLibrary()
{
// Create a pipeline library for the vertex input interface
{
VkGraphicsPipelineLibraryCreateInfoEXT libraryInfo{};
libraryInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT;
libraryInfo.flags = VK_GRAPHICS_PIPELINE_LIBRARY_VERTEX_INPUT_INTERFACE_BIT_EXT;
VkPipelineVertexInputStateCreateInfo vertexInputState = *vkglTF::Vertex::getPipelineVertexInputState({ vkglTF::VertexComponent::Position, vkglTF::VertexComponent::Normal, vkglTF::VertexComponent::Color });
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VkGraphicsPipelineCreateInfo pipelineLibraryCI{};
pipelineLibraryCI.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineLibraryCI.flags = VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT;
pipelineLibraryCI.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineLibraryCI.pNext = &libraryInfo;
pipelineLibraryCI.pInputAssemblyState = &inputAssemblyState;
pipelineLibraryCI.pVertexInputState = &vertexInputState;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineLibraryCI, nullptr, &pipelineLibrary.vertexInputInterface));
}
// Creata a pipeline library for the vertex shader stage
{
VkGraphicsPipelineLibraryCreateInfoEXT libraryInfo{};
libraryInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT;
libraryInfo.flags = VK_GRAPHICS_PIPELINE_LIBRARY_PRE_RASTERIZATION_SHADERS_BIT_EXT;
VkDynamicState vertexDynamicStates[2] = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dynamicInfo{};
dynamicInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicInfo.dynamicStateCount = 2;
dynamicInfo.pDynamicStates = vertexDynamicStates;
VkPipelineViewportStateCreateInfo viewportState = {};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.scissorCount = 1;
VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0);
// @todo: we can skip the pipeline shader module info and directly consume the shader module
ShaderInfo shaderInfo{};
loadShaderFile(getShadersPath() + "graphicspipelinelibrary/shared.vert.spv", shaderInfo);
VkShaderModuleCreateInfo shaderModuleCI{};
shaderModuleCI.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shaderModuleCI.codeSize = shaderInfo.size;
shaderModuleCI.pCode = shaderInfo.code;
VkPipelineShaderStageCreateInfo shaderStageCI{};
shaderStageCI.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStageCI.pNext = &shaderModuleCI;
shaderStageCI.stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStageCI.pName = "main";
VkGraphicsPipelineCreateInfo pipelineLibraryCI{};
pipelineLibraryCI.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineLibraryCI.pNext = &libraryInfo;
pipelineLibraryCI.renderPass = renderPass;
pipelineLibraryCI.flags = VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT;
pipelineLibraryCI.stageCount = 1;
pipelineLibraryCI.pStages = &shaderStageCI;
pipelineLibraryCI.layout = pipelineLayout;
pipelineLibraryCI.pDynamicState = &dynamicInfo;
pipelineLibraryCI.pViewportState = &viewportState;
pipelineLibraryCI.pRasterizationState = &rasterizationState;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineLibraryCI, nullptr, &pipelineLibrary.preRasterizationShaders));
}
// Create a pipeline library for the fragment output interface
{
VkGraphicsPipelineLibraryCreateInfoEXT libraryInfo{};
libraryInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT;
libraryInfo.flags = VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_OUTPUT_INTERFACE_BIT_EXT;
VkPipelineColorBlendAttachmentState blendAttachmentSstate = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentSstate);
VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT);
VkGraphicsPipelineCreateInfo pipelineLibraryCI{};
pipelineLibraryCI.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineLibraryCI.pNext = &libraryInfo;
pipelineLibraryCI.layout = pipelineLayout;
pipelineLibraryCI.renderPass = renderPass;
pipelineLibraryCI.flags = VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT;
pipelineLibraryCI.pColorBlendState = &colorBlendState;
pipelineLibraryCI.pMultisampleState = &multisampleState;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineLibraryCI, nullptr, &pipelineLibrary.fragmentOutputInterface));
}
}
void threadFn()
{
const std::lock_guard<std::mutex> lock(mutex);
auto start = std::chrono::steady_clock::now();
prepareNewPipeline();
newPipelineCreated = true;
// Change viewport/draw count
if (pipelines.size() > splitX * splitY) {
splitX++;
splitY++;
}
auto delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start);
std::cout << "Pipeline created in " << delta.count() << " microseconds\n";
}
// Create a new pipeline using the pipeline library and a customized fragment shader
// Used from a thread
void prepareNewPipeline()
{
// Create the fragment shader part of the pipeline library with some random options
VkGraphicsPipelineLibraryCreateInfoEXT libraryInfo{};
libraryInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT;
libraryInfo.flags = VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT;
VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT);
// Using the pipeline library extension, we can skip the pipeline shader module creation and directly pass the shader code to the pipeline
ShaderInfo shaderInfo{};
loadShaderFile(getShadersPath() + "graphicspipelinelibrary/uber.frag.spv", shaderInfo);
VkShaderModuleCreateInfo shaderModuleCI{};
shaderModuleCI.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shaderModuleCI.codeSize = shaderInfo.size;
shaderModuleCI.pCode = shaderInfo.code;
VkPipelineShaderStageCreateInfo shaderStageCI{};
shaderStageCI.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStageCI.pNext = &shaderModuleCI;
shaderStageCI.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStageCI.pName = "main";
// Select lighting model using a specialization constant
srand((unsigned int)time(NULL));
uint32_t lighting_model = (int)(rand() % 4);
// Each shader constant of a shader stage corresponds to one map entry
VkSpecializationMapEntry specializationMapEntry{};
specializationMapEntry.constantID = 0;
specializationMapEntry.size = sizeof(uint32_t);
VkSpecializationInfo specializationInfo{};
specializationInfo.mapEntryCount = 1;
specializationInfo.pMapEntries = &specializationMapEntry;
specializationInfo.dataSize = sizeof(uint32_t);
specializationInfo.pData = &lighting_model;
shaderStageCI.pSpecializationInfo = &specializationInfo;
VkGraphicsPipelineCreateInfo pipelineCI{};
pipelineCI.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineCI.pNext = &libraryInfo;
pipelineCI.flags = VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT;
pipelineCI.stageCount = 1;
pipelineCI.pStages = &shaderStageCI;
pipelineCI.layout = pipelineLayout;
pipelineCI.renderPass = renderPass;
pipelineCI.pDepthStencilState = &depthStencilState;
pipelineCI.pMultisampleState = &multisampleState;
VkPipeline fragmentShader = VK_NULL_HANDLE;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, threadPipelineCache, 1, &pipelineCI, nullptr, &fragmentShader));
// Create the pipeline using the pre-built pipeline library parts
// Except for above fragment shader part all parts have been pre-built and will be re-used
std::vector<VkPipeline> libraries = {
pipelineLibrary.vertexInputInterface,
pipelineLibrary.preRasterizationShaders,
fragmentShader,
pipelineLibrary.fragmentOutputInterface };
// Link the library parts into a graphics pipeline
VkPipelineLibraryCreateInfoKHR pipelineLibraryCI{};
pipelineLibraryCI.sType = VK_STRUCTURE_TYPE_PIPELINE_LIBRARY_CREATE_INFO_KHR;
pipelineLibraryCI.libraryCount = static_cast<uint32_t>(libraries.size());
pipelineLibraryCI.pLibraries = libraries.data();
// If set to true, we pass VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT which will let the implementation do additional optimizations at link time
// This trades in pipeline creation time for run-time performance
bool optimized = true;
VkGraphicsPipelineCreateInfo executablePipelineCI{};
executablePipelineCI.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
executablePipelineCI.pNext = &pipelineLibraryCI;
executablePipelineCI.layout = pipelineLayout;
if (linkTimeOptimization)
{
// If link time optimization is activated in the UI, we set the VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT flag which will let the implementation do additional optimizations at link time
// This trades in pipeline creation time for run-time performance
executablePipelineCI.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT;
}
VkPipeline executable = VK_NULL_HANDLE;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, threadPipelineCache, 1, &executablePipelineCI, nullptr, &executable));
pipelines.push_back(executable);
// Push fragment shader to list for deletion in the sample's destructor
pipelineLibrary.fragmentShaders.push_back(fragmentShader);
}
// Prepare and initialize uniform buffer containing shader uniforms
void prepareUniformBuffers()
{
// Create the vertex shader uniform buffer block
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffer,
sizeof(uboVS)));
// Map persistent
VK_CHECK_RESULT(uniformBuffer.map());
updateUniformBuffers();
}
void updateUniformBuffers()
{
if (!paused) {
rotation += frameTimer * 0.1f;
}
camera.setPerspective(45.0f, ((float)width / (float)splitX) / ((float)height / (float)splitY), 0.1f, 256.0f);
uboVS.projection = camera.matrices.perspective;
uboVS.modelView = camera.matrices.view * glm::rotate(glm::mat4(1.0f), glm::radians(rotation * 360.0f), glm::vec3(0.0f, 1.0f, 0.0f));
memcpy(uniformBuffer.mapped, &uboVS, sizeof(uboVS));
}
void draw()
{
VulkanExampleBase::prepareFrame();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
void prepare()
{
VulkanExampleBase::prepare();
loadAssets();
prepareUniformBuffers();
setupDescriptorSetLayout();
preparePipelineLibrary();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
// Create a separate pipeline cache for the pipeline creation thread
VkPipelineCacheCreateInfo pipelineCachCI = {};
pipelineCachCI.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
vkCreatePipelineCache(device, &pipelineCachCI, nullptr, &threadPipelineCache);
// Create first pipeline using a background thread
std::thread pipelineGenerationThread(&VulkanExample::threadFn, this);
pipelineGenerationThread.detach();
prepared = true;
}
virtual void render()
{
if (!prepared)
return;
if (newPipelineCreated)
{
newPipelineCreated = false;
vkQueueWaitIdle(queue);
buildCommandBuffers();
}
draw();
updateUniformBuffers();
}
virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay)
{
overlay->checkBox("Link time optimization", &linkTimeOptimization);
if (overlay->button("New pipeline")) {
// Spwan a thread to create a new pipeline in the background
std::thread pipelineGenerationThread(&VulkanExample::threadFn, this);
pipelineGenerationThread.detach();
}
}
};
VULKAN_EXAMPLE_MAIN()