GraphicsPipelineManager.cpp 26.1 KB
Newer Older
1
#include "GraphicsPipelineManager.hpp"
2
#include "vkcv/Image.hpp"
3
#include "vkcv/Logger.hpp"
4
5
6

namespace vkcv
{
7
	
8
9
10
	GraphicsPipelineManager::GraphicsPipelineManager(vk::Device device, vk::PhysicalDevice physicalDevice) noexcept :
            m_Device(device),
            m_physicalDevice(physicalDevice),
11
            m_Pipelines{}
12
    {}
13
14
	
	GraphicsPipelineManager::~GraphicsPipelineManager() noexcept
15
    {
16
17
18
        for (uint64_t id = 0; id < m_Pipelines.size(); id++) {
            destroyPipelineById(id);
        }
19
20
    }

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    // currently assuming default 32 bit formats, no lower precision or normalized variants supported
    vk::Format vertexFormatToVulkanFormat(const VertexAttachmentFormat format) {
        switch (format) {
            case VertexAttachmentFormat::FLOAT:
                return vk::Format::eR32Sfloat;
            case VertexAttachmentFormat::FLOAT2:
                return vk::Format::eR32G32Sfloat;
            case VertexAttachmentFormat::FLOAT3:
                return vk::Format::eR32G32B32Sfloat;
            case VertexAttachmentFormat::FLOAT4:
                return vk::Format::eR32G32B32A32Sfloat;
            case VertexAttachmentFormat::INT:
                return vk::Format::eR32Sint;
            case VertexAttachmentFormat::INT2:
                return vk::Format::eR32G32Sint;
            case VertexAttachmentFormat::INT3:
                return vk::Format::eR32G32B32Sint;
            case VertexAttachmentFormat::INT4:
                return vk::Format::eR32G32B32A32Sint;
            default:
            vkcv_log(LogLevel::WARNING, "Unknown vertex format");
                return vk::Format::eUndefined;
43
44
45
        }
    }

46
47
    vk::PrimitiveTopology primitiveTopologyToVulkanPrimitiveTopology(const PrimitiveTopology topology) {
        switch (topology) {
48
49
50
51
52
53
54
55
56
            case(PrimitiveTopology::PointList):
                return vk::PrimitiveTopology::ePointList;
            case(PrimitiveTopology::LineList):
                return vk::PrimitiveTopology::eLineList;
            case(PrimitiveTopology::TriangleList):
                return vk::PrimitiveTopology::eTriangleList;
            default:
            vkcv_log(LogLevel::ERROR, "Unknown primitive topology type");
                return vk::PrimitiveTopology::eTriangleList;
57
58
59
        }
    }

60
61
    vk::CompareOp depthTestToVkCompareOp(DepthTest depthTest) {
        switch (depthTest) {
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
            case(DepthTest::None):
                return vk::CompareOp::eAlways;
            case(DepthTest::Less):
                return vk::CompareOp::eLess;
            case(DepthTest::LessEqual):
                return vk::CompareOp::eLessOrEqual;
            case(DepthTest::Greater):
                return vk::CompareOp::eGreater;
            case(DepthTest::GreatherEqual):
                return vk::CompareOp::eGreaterOrEqual;
            case(DepthTest::Equal):
                return vk::CompareOp::eEqual;
            default:
                vkcv_log(LogLevel::ERROR, "Unknown depth test enum");
                return vk::CompareOp::eAlways;
77
78
79
        }
    }

80
    vk::ShaderStageFlagBits shaderStageToVkShaderStage(ShaderStage stage) {
81
        switch (stage) {
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
            case ShaderStage::VERTEX:
                return vk::ShaderStageFlagBits::eVertex;
            case ShaderStage::FRAGMENT:
                return vk::ShaderStageFlagBits::eFragment;
            case ShaderStage::GEOMETRY:
                return vk::ShaderStageFlagBits::eGeometry;
            case ShaderStage::TESS_CONTROL:
                return vk::ShaderStageFlagBits::eTessellationControl;
            case ShaderStage::TESS_EVAL:
                return vk::ShaderStageFlagBits::eTessellationEvaluation;
            case ShaderStage::COMPUTE:
                return vk::ShaderStageFlagBits::eCompute;
            case ShaderStage::TASK:
                return vk::ShaderStageFlagBits::eTaskNV;
            case ShaderStage::MESH:
                return vk::ShaderStageFlagBits::eMeshNV;
            default:
                vkcv_log(LogLevel::ERROR, "Unknown shader stage");
                return vk::ShaderStageFlagBits::eAll;
101
        }
102
    }
103

104
    bool createPipelineShaderStageCreateInfo(
105
            const ShaderProgram&          shaderProgram,
106
107
108
            ShaderStage                         stage,
            vk::Device                          device,
            vk::PipelineShaderStageCreateInfo*  outCreateInfo) {
109

110
111
112
113
114
115
        assert(outCreateInfo);
        std::vector<char>           code = shaderProgram.getShader(stage).shaderCode;
        vk::ShaderModuleCreateInfo  vertexModuleInfo({}, code.size(), reinterpret_cast<uint32_t*>(code.data()));
        vk::ShaderModule            shaderModule;
        if (device.createShaderModule(&vertexModuleInfo, nullptr, &shaderModule) != vk::Result::eSuccess)
            return false;
116

117
        const static auto entryName = "main";
118

119
        *outCreateInfo = vk::PipelineShaderStageCreateInfo(
120
121
122
123
124
                {},
                shaderStageToVkShaderStage(stage),
                shaderModule,
                entryName,
                nullptr);
125
        return true;
126
    }
127
128
129
130
131
132
133
134
135
136
137
138
	
	/**
	 * Fills Vertex Attribute and Binding Description with the corresponding objects form the Vertex Layout.
	 * @param vertexAttributeDescriptions
	 * @param vertexBindingDescriptions
	 * @param existsVertexShader
	 * @param config
	 */
	void fillVertexInputDescription(
			std::vector<vk::VertexInputAttributeDescription> &vertexAttributeDescriptions,
			std::vector<vk::VertexInputBindingDescription>   &vertexBindingDescriptions,
			const bool existsVertexShader,
139
			const GraphicsPipelineConfig &config) {
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
		
		if (existsVertexShader) {
			const VertexLayout& layout = config.m_VertexLayout;
			
			// iterate over the layout's specified, mutually exclusive buffer bindings that make up a vertex buffer
			for (const auto& vertexBinding : layout.vertexBindings)
			{
				vertexBindingDescriptions.emplace_back(vertexBinding.bindingLocation,
													   vertexBinding.stride,
													   vk::VertexInputRate::eVertex);
				
				// iterate over the bindings' specified, mutually exclusive vertex input attachments that make up a vertex
				for (const auto& vertexAttachment : vertexBinding.vertexAttachments)
				{
					vertexAttributeDescriptions.emplace_back(vertexAttachment.inputLocation,
															 vertexBinding.bindingLocation,
															 vertexFormatToVulkanFormat(vertexAttachment.format),
															 vertexAttachment.offset % vertexBinding.stride);
				}
			}
		}
	}
	
	/**
	 * Creates a Pipeline Vertex Input State Create Info Struct and fills it with Attribute and Binding data.
	 * @param vertexAttributeDescriptions
	 * @param vertexBindingDescriptions
	 * @return Pipeline Vertex Input State Create Info Struct
	 */
	vk::PipelineVertexInputStateCreateInfo createPipelineVertexInputStateCreateInfo(
			std::vector<vk::VertexInputAttributeDescription> &vertexAttributeDescriptions,
			std::vector<vk::VertexInputBindingDescription>   &vertexBindingDescriptions) {
		
		vk::PipelineVertexInputStateCreateInfo pipelineVertexInputStateCreateInfo(
				{},
				vertexBindingDescriptions.size(),
				vertexBindingDescriptions.data(),
				vertexAttributeDescriptions.size(),
				vertexAttributeDescriptions.data()
		);
		return pipelineVertexInputStateCreateInfo;
	}
	
	/**
	 * Creates a Pipeline Input Assembly State Create Info Struct with 'Primitive Restart' disabled.
	 * @param config provides data for primitive topology.
	 * @return Pipeline Input Assembly State Create Info Struct
	 */
188
	vk::PipelineInputAssemblyStateCreateInfo createPipelineInputAssemblyStateCreateInfo(const GraphicsPipelineConfig &config) {
189
190
191
192
193
194
195
196
197
		vk::PipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo(
				{},
				primitiveTopologyToVulkanPrimitiveTopology(config.m_PrimitiveTopology),
				false
		);
		
		return pipelineInputAssemblyStateCreateInfo;
	}
	
198
199
200
201
202
203
204
205
206
	vk::PipelineTessellationStateCreateInfo createPipelineTessellationStateCreateInfo(const GraphicsPipelineConfig &config) {
		vk::PipelineTessellationStateCreateInfo pipelineTessellationStateCreateInfo(
				{},
				config.m_tessellationControlPoints
		);
		
		return pipelineTessellationStateCreateInfo;
	}
	
207
208
209
210
211
	/**
	 * Creates a Pipeline Viewport State Create Info Struct with default set viewport and scissor settings.
	 * @param config provides with and height of the output window
	 * @return Pipeline Viewport State Create Info Struct
	 */
212
	vk::PipelineViewportStateCreateInfo createPipelineViewportStateCreateInfo(const GraphicsPipelineConfig &config) {
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
		static vk::Viewport viewport;
		static vk::Rect2D scissor;
		
		viewport = vk::Viewport(
				0.f, 0.f,
				static_cast<float>(config.m_Width),
				static_cast<float>(config.m_Height),
				0.f, 1.f
		);
		
		scissor = vk::Rect2D(
				{ 0,0 },
				{ config.m_Width, config.m_Height }
		);
		
		vk::PipelineViewportStateCreateInfo pipelineViewportStateCreateInfo(
				{},
				1,
				&viewport,
				1,
				&scissor
		);
		
		return pipelineViewportStateCreateInfo;
	}
	
	/**
	 * Creates a Pipeline Rasterization State Create Info Struct with default values set to:
	 * Rasterizer Discard: Disabled
	 * Polygon Mode: Fill
	 * Front Face: Counter Clockwise
	 * Depth Bias: Disabled
	 * Line Width: 1.0
	 * Depth Clamping and Culling Mode ist set by the Pipeline Config
	 * @param config sets Depth Clamping and Culling Mode
	 * @return Pipeline Rasterization State Create Info Struct
	 */
250
251
252
	vk::PipelineRasterizationStateCreateInfo createPipelineRasterizationStateCreateInfo(
		const GraphicsPipelineConfig &config,
		const vk::PhysicalDeviceConservativeRasterizationPropertiesEXT& conservativeRasterProperties) {
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
		vk::CullModeFlags cullMode;
		switch (config.m_culling) {
			case CullMode::None:
				cullMode = vk::CullModeFlagBits::eNone;
				break;
			case CullMode::Front:
				cullMode = vk::CullModeFlagBits::eFront;
				break;
			case CullMode::Back:
				cullMode = vk::CullModeFlagBits::eBack;
				break;
			default:
			vkcv_log(LogLevel::ERROR, "Unknown CullMode");
				cullMode = vk::CullModeFlagBits::eNone;
		}
		
		vk::PipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo (
				{},
				config.m_EnableDepthClamping,
				false,
				vk::PolygonMode::eFill,
				cullMode,
				vk::FrontFace::eCounterClockwise,
				false,
				0.f,
				0.f,
				0.f,
				1.f
		);
282

283
284
285
		static vk::PipelineRasterizationConservativeStateCreateInfoEXT conservativeRasterization;
		
		if (config.m_UseConservativeRasterization) {
286
287
288
            const float overestimationSize = 1.0f - conservativeRasterProperties.primitiveOverestimationSize;
            const float maxOverestimationSize = conservativeRasterProperties.maxExtraPrimitiveOverestimationSize;

289
290
291
			conservativeRasterization = vk::PipelineRasterizationConservativeStateCreateInfoEXT(
					{},
					vk::ConservativeRasterizationModeEXT::eOverestimate,
292
					std::min(std::max(overestimationSize, 0.f), maxOverestimationSize)
293
294
295
296
297
298
299
300
301
302
303
304
305
			);
			
			pipelineRasterizationStateCreateInfo.pNext = &conservativeRasterization;
		}
		
		return pipelineRasterizationStateCreateInfo;
	}
	
	/**
	 * Creates a Pipeline Multisample State Create Info Struct.
	 * @param config set MSAA Sample Count Flag
	 * @return Pipeline Multisample State Create Info Struct
	 */
306
	vk::PipelineMultisampleStateCreateInfo createPipelineMultisampleStateCreateInfo(const GraphicsPipelineConfig &config) {
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
		vk::PipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo(
				{},
				msaaToVkSampleCountFlag(config.m_multisampling),
				false,
				0.f,
				nullptr,
				config.m_alphaToCoverage,
				false
		);
		
		return pipelineMultisampleStateCreateInfo;
	}
	
	/**
	 * Creates a Pipeline Color Blend State Create Info Struct.
	 * Currently only one blend mode is supported! There for, blending is set to additive.
	 * @param config sets blend mode
	 * @return
	 */
326
	vk::PipelineColorBlendStateCreateInfo createPipelineColorBlendStateCreateInfo(const GraphicsPipelineConfig &config) {
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
		// currently set to additive, if not disabled
		// BlendFactors must be set as soon as additional BlendModes are added
		static vk::PipelineColorBlendAttachmentState colorBlendAttachmentState (
				config.m_blendMode != BlendMode::None,
				vk::BlendFactor::eOne,
				vk::BlendFactor::eOne,
				vk::BlendOp::eAdd,
				vk::BlendFactor::eOne,
				vk::BlendFactor::eOne,
				vk::BlendOp::eAdd,
				vk::ColorComponentFlags(
						VK_COLOR_COMPONENT_R_BIT |
						VK_COLOR_COMPONENT_G_BIT |
						VK_COLOR_COMPONENT_B_BIT |
						VK_COLOR_COMPONENT_A_BIT
				)
		);
		
		vk::PipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo(
				{},
				false,
				vk::LogicOp::eClear,
				1,	//TODO: hardcoded to one
				&colorBlendAttachmentState,
				{ 1.f,1.f,1.f,1.f }
		);
		
		return pipelineColorBlendStateCreateInfo;
	}
	
	/**
	 * Creates a Pipeline Layout Create Info Struct.
	 * @param config sets Push Constant Size and Descriptor Layouts.
	 * @return Pipeline Layout Create Info Struct
	 */
362
	vk::PipelineLayoutCreateInfo createPipelineLayoutCreateInfo(const GraphicsPipelineConfig &config) {
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
		static vk::PushConstantRange pushConstantRange;
		
		const size_t pushConstantSize = config.m_ShaderProgram.getPushConstantSize();
		pushConstantRange = vk::PushConstantRange(
				vk::ShaderStageFlagBits::eAll, 0, pushConstantSize
		);
		
		vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo(
				{},
				(config.m_DescriptorLayouts),
				(pushConstantRange)
		);
		
		if (pushConstantSize == 0) {
			pipelineLayoutCreateInfo.pushConstantRangeCount = 0;
		}
		
		return pipelineLayoutCreateInfo;
	}
	
	/**
	 * Creates a Pipeline Depth Stencil State Create Info Struct.
	 * @param config sets if depth test in enabled or not.
	 * @return Pipeline Layout Create Info Struct
	 */
388
	vk::PipelineDepthStencilStateCreateInfo createPipelineDepthStencilStateCreateInfo(const GraphicsPipelineConfig &config) {
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
		const vk::PipelineDepthStencilStateCreateInfo pipelineDepthStencilCreateInfo(
				vk::PipelineDepthStencilStateCreateFlags(),
				config.m_depthTest != DepthTest::None,
				config.m_depthWrite,
				depthTestToVkCompareOp(config.m_depthTest),
				false,
				false,
				{},
				{},
				0.0f,
				1.0f
		);
		
		return pipelineDepthStencilCreateInfo;
	}
	
	/**
	 * Creates a Pipeline Dynamic State Create Info Struct.
	 * @param config sets whenever a dynamic viewport is used or not.
	 * @return Pipeline Dynamic State Create Info Struct
	 */
410
	vk::PipelineDynamicStateCreateInfo createPipelineDynamicStateCreateInfo(const GraphicsPipelineConfig &config) {
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
		static std::vector<vk::DynamicState> dynamicStates;
		dynamicStates.clear();
		
		if(config.m_UseDynamicViewport) {
			dynamicStates.push_back(vk::DynamicState::eViewport);
			dynamicStates.push_back(vk::DynamicState::eScissor);
		}
		
		vk::PipelineDynamicStateCreateInfo dynamicStateCreateInfo(
				{},
				static_cast<uint32_t>(dynamicStates.size()),
				dynamicStates.data()
		);
		
		return dynamicStateCreateInfo;
	}
427

428
    GraphicsPipelineHandle GraphicsPipelineManager::createPipeline(const GraphicsPipelineConfig &config, PassManager& passManager) {
429
430
        const vk::RenderPass &pass = passManager.getVkPass(config.m_PassHandle);

431
432
433
        const bool existsTaskShader     = config.m_ShaderProgram.existsShader(ShaderStage::TASK);
        const bool existsMeshShader     = config.m_ShaderProgram.existsShader(ShaderStage::MESH);
        const bool existsVertexShader   = config.m_ShaderProgram.existsShader(ShaderStage::VERTEX);
Artur Wasmut's avatar
Artur Wasmut committed
434
        const bool existsFragmentShader = config.m_ShaderProgram.existsShader(ShaderStage::FRAGMENT);
435
        const bool existsGeometryShader = config.m_ShaderProgram.existsShader(ShaderStage::GEOMETRY);
436
437
438
439
440
441
442
		const bool existsTessellationControlShader = config.m_ShaderProgram.existsShader(ShaderStage::TESS_CONTROL);
		const bool existsTessellationEvaluationShader = config.m_ShaderProgram.existsShader(ShaderStage::TESS_EVAL);
		
        const bool validGeometryStages  = (
				(existsVertexShader && (existsTessellationControlShader == existsTessellationEvaluationShader)) ||
				(existsTaskShader && existsMeshShader)
		);
443

444
        if (!validGeometryStages)
Artur Wasmut's avatar
Artur Wasmut committed
445
        {
446
            vkcv_log(LogLevel::ERROR, "Requires vertex or task and mesh shader");
447
            return GraphicsPipelineHandle();
448
        }
449

450
451
        if (!existsFragmentShader) {
            vkcv_log(LogLevel::ERROR, "Requires fragment shader code");
452
            return GraphicsPipelineHandle();
453
454
        }

455
456
457
458
459
460
461
462
463
464
465
        std::vector<vk::PipelineShaderStageCreateInfo> shaderStages;
        auto destroyShaderModules = [&shaderStages, this] {
            for (auto stage : shaderStages) {
                m_Device.destroyShaderModule(stage.module);
            }
            shaderStages.clear();
        };

        if (existsVertexShader) {
            vk::PipelineShaderStageCreateInfo createInfo;
            const bool success = createPipelineShaderStageCreateInfo(
466
                    config.m_ShaderProgram,
467
                    ShaderStage::VERTEX,
468
469
                    m_Device,
                    &createInfo);
470
471
472
473
474
475

            if (success) {
                shaderStages.push_back(createInfo);
            }
            else {
                destroyShaderModules();
476
                return GraphicsPipelineHandle();
477
478
            }
        }
479

480
481
482
        if (existsTaskShader) {
            vk::PipelineShaderStageCreateInfo createInfo;
            const bool success = createPipelineShaderStageCreateInfo(
483
                    config.m_ShaderProgram,
484
                    ShaderStage::TASK,
485
486
                    m_Device,
                    &createInfo);
487

488
489
490
491
492
            if (success) {
                shaderStages.push_back(createInfo);
            }
            else {
                destroyShaderModules();
493
                return GraphicsPipelineHandle();
494
495
            }
        }
496

497
498
499
        if (existsMeshShader) {
            vk::PipelineShaderStageCreateInfo createInfo;
            const bool success = createPipelineShaderStageCreateInfo(
500
                    config.m_ShaderProgram,
501
                    ShaderStage::MESH,
502
503
                    m_Device,
                    &createInfo);
504
505
506
507
508
509

            if (success) {
                shaderStages.push_back(createInfo);
            }
            else {
                destroyShaderModules();
510
                return GraphicsPipelineHandle();
511
            }
512
513
514
        }

        {
515
516
            vk::PipelineShaderStageCreateInfo createInfo;
            const bool success = createPipelineShaderStageCreateInfo(
517
                    config.m_ShaderProgram,
518
519
520
521
522
523
524
525
526
                    ShaderStage::FRAGMENT,
                    m_Device,
                    &createInfo);

            if (success) {
                shaderStages.push_back(createInfo);
            }
            else {
                destroyShaderModules();
527
                return GraphicsPipelineHandle();
528
529
530
531
532
533
534
535
            }
        }

        if (existsGeometryShader) {
            vk::PipelineShaderStageCreateInfo createInfo;
            const bool success = createPipelineShaderStageCreateInfo(
                    config.m_ShaderProgram,
                    ShaderStage::GEOMETRY,
536
537
                    m_Device,
                    &createInfo);
538
539
540
541
542
543

            if (success) {
                shaderStages.push_back(createInfo);
            }
            else {
                destroyShaderModules();
544
                return GraphicsPipelineHandle();
545
            }
546
        }
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
	
		if (existsTessellationControlShader) {
			vk::PipelineShaderStageCreateInfo createInfo;
			const bool success = createPipelineShaderStageCreateInfo(
					config.m_ShaderProgram,
					ShaderStage::TESS_CONTROL,
					m_Device,
					&createInfo);
		
			if (success) {
				shaderStages.push_back(createInfo);
			}
			else {
				destroyShaderModules();
				return GraphicsPipelineHandle();
			}
		}
	
		if (existsTessellationEvaluationShader) {
			vk::PipelineShaderStageCreateInfo createInfo;
			const bool success = createPipelineShaderStageCreateInfo(
					config.m_ShaderProgram,
					ShaderStage::TESS_EVAL,
					m_Device,
					&createInfo);
		
			if (success) {
				shaderStages.push_back(createInfo);
			}
			else {
				destroyShaderModules();
				return GraphicsPipelineHandle();
			}
		}
581

582
583
        // vertex input state
        // Fill up VertexInputBindingDescription and VertexInputAttributeDescription Containers
584
        std::vector<vk::VertexInputAttributeDescription>	vertexAttributeDescriptions;
585
        std::vector<vk::VertexInputBindingDescription>		vertexBindingDescriptions;
586
        fillVertexInputDescription(vertexAttributeDescriptions, vertexBindingDescriptions, existsVertexShader, config);
587

588
        // Handover Containers to PipelineVertexInputStateCreateIngo Struct
589
590
591
        vk::PipelineVertexInputStateCreateInfo pipelineVertexInputStateCreateInfo =
                createPipelineVertexInputStateCreateInfo(vertexAttributeDescriptions,
                                                         vertexBindingDescriptions);
592
593

        // input assembly state
594
595
        vk::PipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo =
                createPipelineInputAssemblyStateCreateInfo(config);
596

597
598
599
600
		// tesselation state
		vk::PipelineTessellationStateCreateInfo pipelineTessellationStateCreateInfo =
				createPipelineTessellationStateCreateInfo(config);
		
601
        // viewport state
602
603
        vk::PipelineViewportStateCreateInfo pipelineViewportStateCreateInfo =
                createPipelineViewportStateCreateInfo(config);
604
605

        // rasterization state
606
607
608
609
610
        vk::PhysicalDeviceConservativeRasterizationPropertiesEXT    conservativeRasterProperties;
        vk::PhysicalDeviceProperties                                deviceProperties;
        vk::PhysicalDeviceProperties2                               deviceProperties2(deviceProperties);
        deviceProperties2.pNext = &conservativeRasterProperties;
        m_physicalDevice.getProperties2(&deviceProperties2);
611
        vk::PipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo =
612
                createPipelineRasterizationStateCreateInfo(config, conservativeRasterProperties);
613
614

        // multisample state
615
616
        vk::PipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo =
                createPipelineMultisampleStateCreateInfo(config);
617
618

        // color blend state
619
620
        vk::PipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo =
                createPipelineColorBlendStateCreateInfo(config);
621

622
623
624
        // Dynamic State
        vk::PipelineDynamicStateCreateInfo dynamicStateCreateInfo =
                createPipelineDynamicStateCreateInfo(config);
625

626
        // pipeline layout
627
628
        vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo =
                createPipelineLayoutCreateInfo(config);
Alexander Gauggel's avatar
Alexander Gauggel committed
629

630
        vk::PipelineLayout vkPipelineLayout{};
631
        if (m_Device.createPipelineLayout(&pipelineLayoutCreateInfo, nullptr, &vkPipelineLayout) != vk::Result::eSuccess) {
632
            destroyShaderModules();
633
            return GraphicsPipelineHandle();
634
        }
635

636
        // Depth Stencil
637
638
        const vk::PipelineDepthStencilStateCreateInfo depthStencilCreateInfo =
                createPipelineDepthStencilStateCreateInfo(config);
639
640
641
642
643
644
645
646
647
648
649

        const vk::PipelineDepthStencilStateCreateInfo* p_depthStencilCreateInfo = nullptr;
        const PassConfig& passConfig = passManager.getPassConfig(config.m_PassHandle);

        for (const auto& attachment : passConfig.attachments) {
            if (isDepthFormat(attachment.format)) {
                p_depthStencilCreateInfo = &depthStencilCreateInfo;
                break;
            }
        }

650
        // Get all setting structs together and create the Pipeline
651
        const vk::GraphicsPipelineCreateInfo graphicsPipelineCreateInfo(
652
653
654
655
656
                {},
                static_cast<uint32_t>(shaderStages.size()),
                shaderStages.data(),
                &pipelineVertexInputStateCreateInfo,
                &pipelineInputAssemblyStateCreateInfo,
657
                &pipelineTessellationStateCreateInfo,
658
659
660
                &pipelineViewportStateCreateInfo,
                &pipelineRasterizationStateCreateInfo,
                &pipelineMultisampleStateCreateInfo,
661
                p_depthStencilCreateInfo,
662
                &pipelineColorBlendStateCreateInfo,
663
                &dynamicStateCreateInfo,
664
665
666
667
668
669
670
671
672
673
                vkPipelineLayout,
                pass,
                0,
                {},
                0
        );

        vk::Pipeline vkPipeline{};
        if (m_Device.createGraphicsPipelines(nullptr, 1, &graphicsPipelineCreateInfo, nullptr, &vkPipeline) != vk::Result::eSuccess)
        {
674
675
            // Catch runtime error if the creation of the pipeline fails.
            // Destroy everything to keep the memory clean.
676
            destroyShaderModules();
677
            return GraphicsPipelineHandle();
678
679
        }

680
        // Clean Up
681
        destroyShaderModules();
682

683
        // Hand over Handler to main Application
684
        const uint64_t id = m_Pipelines.size();
685
        m_Pipelines.push_back({ vkPipeline, vkPipelineLayout, config });
686
        return GraphicsPipelineHandle(id, [&](uint64_t id) { destroyPipelineById(id); });
687
688
    }

689
    vk::Pipeline GraphicsPipelineManager::getVkPipeline(const GraphicsPipelineHandle &handle) const
690
    {
691
692
693
694
695
696
697
698
699
        const uint64_t id = handle.getId();

        if (id >= m_Pipelines.size()) {
            return nullptr;
        }

        auto& pipeline = m_Pipelines[id];

        return pipeline.m_handle;
700
701
    }

702
    vk::PipelineLayout GraphicsPipelineManager::getVkPipelineLayout(const GraphicsPipelineHandle &handle) const
703
    {
704
705
706
707
708
709
710
711
        const uint64_t id = handle.getId();

        if (id >= m_Pipelines.size()) {
            return nullptr;
        }

        auto& pipeline = m_Pipelines[id];

712
713
        return pipeline.m_layout;
    }
714

715
    void GraphicsPipelineManager::destroyPipelineById(uint64_t id) {
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
        if (id >= m_Pipelines.size()) {
            return;
        }

        auto& pipeline = m_Pipelines[id];

        if (pipeline.m_handle) {
            m_Device.destroy(pipeline.m_handle);
            pipeline.m_handle = nullptr;
        }

        if (pipeline.m_layout) {
            m_Device.destroy(pipeline.m_layout);
            pipeline.m_layout = nullptr;
        }
731
    }
732

733
    const GraphicsPipelineConfig& GraphicsPipelineManager::getPipelineConfig(const GraphicsPipelineHandle &handle) const
734
735
    {
        const uint64_t id = handle.getId();
736

737
        if (id >= m_Pipelines.size()) {
738
            static GraphicsPipelineConfig dummyConfig;
739
740
            vkcv_log(LogLevel::ERROR, "Invalid handle");
            return dummyConfig;
741
        }
742

743
        return m_Pipelines[id].m_config;
744
    }
745
}