forked from SaschaWillems/Vulkan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deferredshadows.cpp
1190 lines (1006 loc) · 41.4 KB
/
deferredshadows.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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Vulkan Example - Deferred shading with shadows from multiple light sources using geometry shader instancing
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <vector>
#include <algorithm>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vulkan/vulkan.h>
#include "vulkanexamplebase.h"
#include "VulkanBuffer.hpp"
#include "VulkanFrameBuffer.hpp"
#include "VulkanTexture.hpp"
#include "VulkanModel.hpp"
#define VERTEX_BUFFER_BIND_ID 0
#define ENABLE_VALIDATION false
// Shadowmap properties
#if defined(__ANDROID__)
#define SHADOWMAP_DIM 1024
#else
#define SHADOWMAP_DIM 2048
#endif
// 16 bits of depth is enough for such a small scene
#define SHADOWMAP_FORMAT VK_FORMAT_D32_SFLOAT_S8_UINT
#if defined(__ANDROID__)
// Use max. screen dimension as deferred framebuffer size
#define FB_DIM std::max(width,height)
#else
#define FB_DIM 2048
#endif
// Must match the LIGHT_COUNT define in the shadow and deferred shaders
#define LIGHT_COUNT 3
class VulkanExample : public VulkanExampleBase
{
public:
bool debugDisplay = false;
bool enableShadows = true;
// Keep depth range as small as possible
// for better shadow map precision
float zNear = 0.1f;
float zFar = 64.0f;
float lightFOV = 100.0f;
// Depth bias (and slope) are used to avoid shadowing artefacts
float depthBiasConstant = 1.25f;
float depthBiasSlope = 1.75f;
struct {
struct {
vks::Texture2D colorMap;
vks::Texture2D normalMap;
} model;
struct {
vks::Texture2D colorMap;
vks::Texture2D normalMap;
} background;
} textures;
// Vertex layout for the models
vks::VertexLayout vertexLayout = vks::VertexLayout({
vks::VERTEX_COMPONENT_POSITION,
vks::VERTEX_COMPONENT_UV,
vks::VERTEX_COMPONENT_COLOR,
vks::VERTEX_COMPONENT_NORMAL,
vks::VERTEX_COMPONENT_TANGENT,
});
struct {
vks::Model model;
vks::Model background;
vks::Model quad;
} models;
struct {
VkPipelineVertexInputStateCreateInfo inputState;
std::vector<VkVertexInputBindingDescription> bindingDescriptions;
std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
} vertices;
struct {
glm::mat4 projection;
glm::mat4 model;
glm::mat4 view;
glm::vec4 instancePos[3];
int layer;
} uboVS, uboOffscreenVS;
// This UBO stores the shadow matrices for all of the light sources
// The matrices are indexed using geometry shader instancing
// The instancePos is used to place the models using instanced draws
struct {
glm::mat4 mvp[LIGHT_COUNT];
glm::vec4 instancePos[3];
} uboShadowGS;
struct Light {
glm::vec4 position;
glm::vec4 target;
glm::vec4 color;
glm::mat4 viewMatrix;
};
struct {
glm::vec4 viewPos;
Light lights[LIGHT_COUNT];
uint32_t useShadows = 1;
} uboFragmentLights;
struct {
vks::Buffer vsFullScreen;
vks::Buffer vsOffscreen;
vks::Buffer fsLights;
vks::Buffer uboShadowGS;
} uniformBuffers;
struct {
VkPipeline deferred;
VkPipeline offscreen;
VkPipeline debug;
VkPipeline shadowpass;
} pipelines;
struct {
//todo: rename, shared with deferred and shadow pass
VkPipelineLayout deferred;
VkPipelineLayout offscreen;
} pipelineLayouts;
struct {
VkDescriptorSet model;
VkDescriptorSet background;
VkDescriptorSet shadow;
} descriptorSets;
VkDescriptorSet descriptorSet;
VkDescriptorSetLayout descriptorSetLayout;
struct
{
// Framebuffer resources for the deferred pass
vks::Framebuffer *deferred;
// Framebuffer resources for the shadow pass
vks::Framebuffer *shadow;
} frameBuffers;
struct {
VkCommandBuffer deferred = VK_NULL_HANDLE;
} commandBuffers;
// Semaphore used to synchronize between offscreen and final scene rendering
VkSemaphore offscreenSemaphore = VK_NULL_HANDLE;
VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION)
{
title = "Deferred shading with shadows";
camera.type = Camera::CameraType::firstperson;
#if defined(__ANDROID__)
camera.movementSpeed = 2.5f;
#else
camera.movementSpeed = 5.0f;
camera.rotationSpeed = 0.25f;
#endif
camera.position = { 2.15f, 0.3f, -8.75f };
camera.setRotation(glm::vec3(-0.75f, 12.5f, 0.0f));
camera.setPerspective(60.0f, (float)width / (float)height, zNear, zFar);
timerSpeed *= 0.25f;
paused = true;
settings.overlay = true;
}
~VulkanExample()
{
// Frame buffers
if (frameBuffers.deferred)
{
delete frameBuffers.deferred;
}
if (frameBuffers.shadow)
{
delete frameBuffers.shadow;
}
vkDestroyPipeline(device, pipelines.deferred, nullptr);
vkDestroyPipeline(device, pipelines.offscreen, nullptr);
vkDestroyPipeline(device, pipelines.shadowpass, nullptr);
vkDestroyPipeline(device, pipelines.debug, nullptr);
vkDestroyPipelineLayout(device, pipelineLayouts.deferred, nullptr);
vkDestroyPipelineLayout(device, pipelineLayouts.offscreen, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
// Meshes
models.model.destroy();
models.background.destroy();
models.quad.destroy();
// Uniform buffers
uniformBuffers.vsOffscreen.destroy();
uniformBuffers.vsFullScreen.destroy();
uniformBuffers.fsLights.destroy();
uniformBuffers.uboShadowGS.destroy();
vkFreeCommandBuffers(device, cmdPool, 1, &commandBuffers.deferred);
// Textures
textures.model.colorMap.destroy();
textures.model.normalMap.destroy();
textures.background.colorMap.destroy();
textures.background.normalMap.destroy();
vkDestroySemaphore(device, offscreenSemaphore, nullptr);
}
// Enable physical device features required for this example
virtual void getEnabledFeatures()
{
// Geometry shader support is required for writing to multiple shadow map layers in one single pass
if (deviceFeatures.geometryShader) {
enabledFeatures.geometryShader = VK_TRUE;
}
else {
vks::tools::exitFatal("Selected GPU does not support geometry shaders!", VK_ERROR_FEATURE_NOT_PRESENT);
}
// Enable anisotropic filtering if supported
if (deviceFeatures.samplerAnisotropy) {
enabledFeatures.samplerAnisotropy = VK_TRUE;
}
// Enable texture compression
if (deviceFeatures.textureCompressionBC) {
enabledFeatures.textureCompressionBC = VK_TRUE;
}
else if (deviceFeatures.textureCompressionASTC_LDR) {
enabledFeatures.textureCompressionASTC_LDR = VK_TRUE;
}
else if (deviceFeatures.textureCompressionETC2) {
enabledFeatures.textureCompressionETC2 = VK_TRUE;
}
}
// Prepare a layered shadow map with each layer containing depth from a light's point of view
// The shadow mapping pass uses geometry shader instancing to output the scene from the different
// light sources' point of view to the layers of the depth attachment in one single pass
void shadowSetup()
{
frameBuffers.shadow = new vks::Framebuffer(vulkanDevice);
frameBuffers.shadow->width = SHADOWMAP_DIM;
frameBuffers.shadow->height = SHADOWMAP_DIM;
// Create a layered depth attachment for rendering the depth maps from the lights' point of view
// Each layer corresponds to one of the lights
// The actual output to the separate layers is done in the geometry shader using shader instancing
// We will pass the matrices of the lights to the GS that selects the layer by the current invocation
vks::AttachmentCreateInfo attachmentInfo = {};
attachmentInfo.format = SHADOWMAP_FORMAT;
attachmentInfo.width = SHADOWMAP_DIM;
attachmentInfo.height = SHADOWMAP_DIM;
attachmentInfo.layerCount = LIGHT_COUNT;
attachmentInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
frameBuffers.shadow->addAttachment(attachmentInfo);
// Create sampler to sample from to depth attachment
// Used to sample in the fragment shader for shadowed rendering
VK_CHECK_RESULT(frameBuffers.shadow->createSampler(VK_FILTER_LINEAR, VK_FILTER_LINEAR, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE));
// Create default renderpass for the framebuffer
VK_CHECK_RESULT(frameBuffers.shadow->createRenderPass());
}
// Prepare the framebuffer for offscreen rendering with multiple attachments used as render targets inside the fragment shaders
void deferredSetup()
{
frameBuffers.deferred = new vks::Framebuffer(vulkanDevice);
frameBuffers.deferred->width = FB_DIM;
frameBuffers.deferred->height = FB_DIM;
// Four attachments (3 color, 1 depth)
vks::AttachmentCreateInfo attachmentInfo = {};
attachmentInfo.width = FB_DIM;
attachmentInfo.height = FB_DIM;
attachmentInfo.layerCount = 1;
attachmentInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
// Color attachments
// Attachment 0: (World space) Positions
attachmentInfo.format = VK_FORMAT_R16G16B16A16_SFLOAT;
frameBuffers.deferred->addAttachment(attachmentInfo);
// Attachment 1: (World space) Normals
attachmentInfo.format = VK_FORMAT_R16G16B16A16_SFLOAT;
frameBuffers.deferred->addAttachment(attachmentInfo);
// Attachment 2: Albedo (color)
attachmentInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
frameBuffers.deferred->addAttachment(attachmentInfo);
// Depth attachment
// Find a suitable depth format
VkFormat attDepthFormat;
VkBool32 validDepthFormat = vks::tools::getSupportedDepthFormat(physicalDevice, &attDepthFormat);
assert(validDepthFormat);
attachmentInfo.format = attDepthFormat;
attachmentInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
frameBuffers.deferred->addAttachment(attachmentInfo);
// Create sampler to sample from the color attachments
VK_CHECK_RESULT(frameBuffers.deferred->createSampler(VK_FILTER_NEAREST, VK_FILTER_NEAREST, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE));
// Create default renderpass for the framebuffer
VK_CHECK_RESULT(frameBuffers.deferred->createRenderPass());
}
// Put render commands for the scene into the given command buffer
void renderScene(VkCommandBuffer cmdBuffer, bool shadow)
{
VkDeviceSize offsets[1] = { 0 };
// Background
vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayouts.offscreen, 0, 1, shadow ? &descriptorSets.shadow : &descriptorSets.background, 0, NULL);
vkCmdBindVertexBuffers(cmdBuffer, VERTEX_BUFFER_BIND_ID, 1, &models.background.vertices.buffer, offsets);
vkCmdBindIndexBuffer(cmdBuffer, models.background.indices.buffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(cmdBuffer, models.background.indexCount, 1, 0, 0, 0);
// Objects
vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayouts.offscreen, 0, 1, shadow ? &descriptorSets.shadow : &descriptorSets.model, 0, NULL);
vkCmdBindVertexBuffers(cmdBuffer, VERTEX_BUFFER_BIND_ID, 1, &models.model.vertices.buffer, offsets);
vkCmdBindIndexBuffer(cmdBuffer, models.model.indices.buffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(cmdBuffer, models.model.indexCount, 3, 0, 0, 0);
}
// Build a secondary command buffer for rendering the scene values to the offscreen frame buffer attachments
void buildDeferredCommandBuffer()
{
if (commandBuffers.deferred == VK_NULL_HANDLE)
{
commandBuffers.deferred = VulkanExampleBase::createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, false);
}
// Create a semaphore used to synchronize offscreen rendering and usage
VkSemaphoreCreateInfo semaphoreCreateInfo = vks::initializers::semaphoreCreateInfo();
VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &offscreenSemaphore));
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo();
std::array<VkClearValue, 4> clearValues = {};
VkViewport viewport;
VkRect2D scissor;
// First pass: Shadow map generation
// -------------------------------------------------------------------------------------------------------
clearValues[0].depthStencil = { 1.0f, 0 };
renderPassBeginInfo.renderPass = frameBuffers.shadow->renderPass;
renderPassBeginInfo.framebuffer = frameBuffers.shadow->framebuffer;
renderPassBeginInfo.renderArea.extent.width = frameBuffers.shadow->width;
renderPassBeginInfo.renderArea.extent.height = frameBuffers.shadow->height;
renderPassBeginInfo.clearValueCount = 1;
renderPassBeginInfo.pClearValues = clearValues.data();
VK_CHECK_RESULT(vkBeginCommandBuffer(commandBuffers.deferred, &cmdBufInfo));
viewport = vks::initializers::viewport((float)frameBuffers.shadow->width, (float)frameBuffers.shadow->height, 0.0f, 1.0f);
vkCmdSetViewport(commandBuffers.deferred, 0, 1, &viewport);
scissor = vks::initializers::rect2D(frameBuffers.shadow->width, frameBuffers.shadow->height, 0, 0);
vkCmdSetScissor(commandBuffers.deferred, 0, 1, &scissor);
// Set depth bias (aka "Polygon offset")
vkCmdSetDepthBias(
commandBuffers.deferred,
depthBiasConstant,
0.0f,
depthBiasSlope);
vkCmdBeginRenderPass(commandBuffers.deferred, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(commandBuffers.deferred, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.shadowpass);
renderScene(commandBuffers.deferred, true);
vkCmdEndRenderPass(commandBuffers.deferred);
// Second pass: Deferred calculations
// -------------------------------------------------------------------------------------------------------
// Clear values for all attachments written in the fragment sahder
clearValues[0].color = { { 0.0f, 0.0f, 0.0f, 0.0f } };
clearValues[1].color = { { 0.0f, 0.0f, 0.0f, 0.0f } };
clearValues[2].color = { { 0.0f, 0.0f, 0.0f, 0.0f } };
clearValues[3].depthStencil = { 1.0f, 0 };
renderPassBeginInfo.renderPass = frameBuffers.deferred->renderPass;
renderPassBeginInfo.framebuffer = frameBuffers.deferred->framebuffer;
renderPassBeginInfo.renderArea.extent.width = frameBuffers.deferred->width;
renderPassBeginInfo.renderArea.extent.height = frameBuffers.deferred->height;
renderPassBeginInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
renderPassBeginInfo.pClearValues = clearValues.data();
vkCmdBeginRenderPass(commandBuffers.deferred, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
viewport = vks::initializers::viewport((float)frameBuffers.deferred->width, (float)frameBuffers.deferred->height, 0.0f, 1.0f);
vkCmdSetViewport(commandBuffers.deferred, 0, 1, &viewport);
scissor = vks::initializers::rect2D(frameBuffers.deferred->width, frameBuffers.deferred->height, 0, 0);
vkCmdSetScissor(commandBuffers.deferred, 0, 1, &scissor);
vkCmdBindPipeline(commandBuffers.deferred, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.offscreen);
renderScene(commandBuffers.deferred, false);
vkCmdEndRenderPass(commandBuffers.deferred);
VK_CHECK_RESULT(vkEndCommandBuffer(commandBuffers.deferred));
}
void loadAssets()
{
models.model.loadFromFile(getAssetPath() + "models/armor/armor.dae", vertexLayout, 1.0f, vulkanDevice, queue);
vks::ModelCreateInfo modelCreateInfo;
modelCreateInfo.scale = glm::vec3(15.0f);
modelCreateInfo.uvscale = glm::vec2(1.0f, 1.5f);
modelCreateInfo.center = glm::vec3(0.0f, 2.3f, 0.0f);
models.background.loadFromFile(getAssetPath() + "models/openbox.dae", vertexLayout, &modelCreateInfo, vulkanDevice, queue);
// Textures
std::string texFormatSuffix;
VkFormat texFormat;
// Get supported compressed texture format
if (vulkanDevice->features.textureCompressionBC) {
texFormatSuffix = "_bc3_unorm";
texFormat = VK_FORMAT_BC3_UNORM_BLOCK;
}
else if (vulkanDevice->features.textureCompressionASTC_LDR) {
texFormatSuffix = "_astc_8x8_unorm";
texFormat = VK_FORMAT_ASTC_8x8_UNORM_BLOCK;
}
else if (vulkanDevice->features.textureCompressionETC2) {
texFormatSuffix = "_etc2_unorm";
texFormat = VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;
}
else {
vks::tools::exitFatal("Device does not support any compressed texture format!", VK_ERROR_FEATURE_NOT_PRESENT);
}
textures.model.colorMap.loadFromFile(getAssetPath() + "models/armor/color" + texFormatSuffix + ".ktx", texFormat, vulkanDevice, queue);
textures.model.normalMap.loadFromFile(getAssetPath() + "models/armor/normal" + texFormatSuffix + ".ktx", texFormat, vulkanDevice, queue);
textures.background.colorMap.loadFromFile(getAssetPath() + "textures/stonefloor02_color" + texFormatSuffix + ".ktx", texFormat, vulkanDevice, queue);
textures.background.normalMap.loadFromFile(getAssetPath() + "textures/stonefloor02_normal" + texFormatSuffix + ".ktx", texFormat, vulkanDevice, queue);
}
void reBuildCommandBuffers()
{
if (!checkCommandBuffers())
{
destroyCommandBuffers();
createCommandBuffers();
}
buildCommandBuffers();
}
void buildCommandBuffers()
{
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = { { 0.0f, 0.0f, 0.2f, 0.0f } };
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)
{
// Set target frame buffer
renderPassBeginInfo.framebuffer = VulkanExampleBase::frameBuffers[i];
VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo));
vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f);
vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport);
VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0);
vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor);
VkDeviceSize offsets[1] = { 0 };
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayouts.deferred, 0, 1, &descriptorSet, 0, NULL);
// Final composition as full screen quad
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.deferred);
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &models.quad.vertices.buffer, offsets);
vkCmdBindIndexBuffer(drawCmdBuffers[i], models.quad.indices.buffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(drawCmdBuffers[i], 6, 1, 0, 0, 0);
if (debugDisplay)
{
// Visualize depth maps
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.debug);
vkCmdDrawIndexed(drawCmdBuffers[i], 6, LIGHT_COUNT, 0, 0, 0);
}
drawUI(drawCmdBuffers[i]);
vkCmdEndRenderPass(drawCmdBuffers[i]);
VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i]));
}
}
/** @brief Create a single quad for fullscreen deferred pass and debug passes (debug pass uses instancing for light visualization) */
void generateQuads()
{
struct Vertex {
float pos[3];
float uv[2];
float col[3];
float normal[3];
float tangent[3];
};
std::vector<Vertex> vertexBuffer;
vertexBuffer.push_back({ { 1.0f, 1.0f, 0.0f },{ 1.0f, 1.0f },{ 1.0f, 1.0f, 1.0f },{ 0.0f, 0.0f, 0.0f } });
vertexBuffer.push_back({ { 0.0f, 1.0f, 0.0f },{ 0.0f, 1.0f },{ 1.0f, 1.0f, 1.0f },{ 0.0f, 0.0f, 0.0f } });
vertexBuffer.push_back({ { 0.0f, 0.0f, 0.0f },{ 0.0f, 0.0f },{ 1.0f, 1.0f, 1.0f },{ 0.0f, 0.0f, 0.0f } });
vertexBuffer.push_back({ { 1.0f, 0.0f, 0.0f },{ 1.0f, 0.0f },{ 1.0f, 1.0f, 1.0f },{ 0.0f, 0.0f, 0.0f } });
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
vertexBuffer.size() * sizeof(Vertex),
&models.quad.vertices.buffer,
&models.quad.vertices.memory,
vertexBuffer.data()));
// Setup indices
std::vector<uint32_t> indexBuffer = { 0,1,2, 2,3,0 };
for (uint32_t i = 0; i < 3; ++i)
{
uint32_t indices[6] = { 0,1,2, 2,3,0 };
for (auto index : indices)
{
indexBuffer.push_back(i * 4 + index);
}
}
models.quad.indexCount = static_cast<uint32_t>(indexBuffer.size());
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
indexBuffer.size() * sizeof(uint32_t),
&models.quad.indices.buffer,
&models.quad.indices.memory,
indexBuffer.data()));
models.quad.device = device;
}
void setupVertexDescriptions()
{
// Binding description
vertices.bindingDescriptions.resize(1);
vertices.bindingDescriptions[0] =
vks::initializers::vertexInputBindingDescription(
VERTEX_BUFFER_BIND_ID,
vertexLayout.stride(),
VK_VERTEX_INPUT_RATE_VERTEX);
// Attribute descriptions
vertices.attributeDescriptions.resize(5);
// Location 0: Position
vertices.attributeDescriptions[0] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
0,
VK_FORMAT_R32G32B32_SFLOAT,
0);
// Location 1: Texture coordinates
vertices.attributeDescriptions[1] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
1,
VK_FORMAT_R32G32_SFLOAT,
sizeof(float) * 3);
// Location 2: Color
vertices.attributeDescriptions[2] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
2,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 5);
// Location 3: Normal
vertices.attributeDescriptions[3] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
3,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 8);
// Location 4: Tangent
vertices.attributeDescriptions[4] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
4,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 11);
vertices.inputState = vks::initializers::pipelineVertexInputStateCreateInfo();
vertices.inputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertices.bindingDescriptions.size());
vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data();
vertices.inputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertices.attributeDescriptions.size());
vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data();
}
void setupDescriptorPool()
{
std::vector<VkDescriptorPoolSize> poolSizes =
{
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 12), //todo: separate set layouts
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 16)
};
VkDescriptorPoolCreateInfo descriptorPoolInfo =
vks::initializers::descriptorPoolCreateInfo(
static_cast<uint32_t>(poolSizes.size()),
poolSizes.data(),
4);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout()
{
// todo: split for clarity, esp. with GS instancing
// Deferred shading layout (Shared with debug display)
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings =
{
// Binding 0: Vertex shader uniform buffer
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT,
0),
// Binding 1: Position texture
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
1),
// Binding 2: Normals texture
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
2),
// Binding 3: Albedo texture
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
3),
// Binding 4: Fragment shader uniform buffer
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_FRAGMENT_BIT,
4),
// Binding 5: Shadow map
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
5),
};
VkDescriptorSetLayoutCreateInfo descriptorLayout =
vks::initializers::descriptorSetLayoutCreateInfo(
setLayoutBindings.data(),
static_cast<uint32_t>(setLayoutBindings.size()));
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo =
vks::initializers::pipelineLayoutCreateInfo(
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayouts.deferred));
// Offscreen (scene) rendering pipeline layout
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayouts.offscreen));
}
void setupDescriptorSet()
{
std::vector<VkWriteDescriptorSet> writeDescriptorSets;
// Textured quad descriptor set
VkDescriptorSetAllocateInfo allocInfo =
vks::initializers::descriptorSetAllocateInfo(
descriptorPool,
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
// Image descriptors for the offscreen color attachments
VkDescriptorImageInfo texDescriptorPosition =
vks::initializers::descriptorImageInfo(
frameBuffers.deferred->sampler,
frameBuffers.deferred->attachments[0].view,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
VkDescriptorImageInfo texDescriptorNormal =
vks::initializers::descriptorImageInfo(
frameBuffers.deferred->sampler,
frameBuffers.deferred->attachments[1].view,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
VkDescriptorImageInfo texDescriptorAlbedo =
vks::initializers::descriptorImageInfo(
frameBuffers.deferred->sampler,
frameBuffers.deferred->attachments[2].view,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
VkDescriptorImageInfo texDescriptorShadowMap =
vks::initializers::descriptorImageInfo(
frameBuffers.shadow->sampler,
frameBuffers.shadow->attachments[0].view,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL);
writeDescriptorSets = {
// Binding 0: Vertex shader uniform buffer
vks::initializers::writeDescriptorSet(
descriptorSet,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
0,
&uniformBuffers.vsFullScreen.descriptor),
// Binding 1: World space position texture
vks::initializers::writeDescriptorSet(
descriptorSet,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1,
&texDescriptorPosition),
// Binding 2: World space normals texture
vks::initializers::writeDescriptorSet(
descriptorSet,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2,
&texDescriptorNormal),
// Binding 3: Albedo texture
vks::initializers::writeDescriptorSet(
descriptorSet,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
3,
&texDescriptorAlbedo),
// Binding 4: Fragment shader uniform buffer
vks::initializers::writeDescriptorSet(
descriptorSet,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
4,
&uniformBuffers.fsLights.descriptor),
// Binding 5: Shadow map
vks::initializers::writeDescriptorSet(
descriptorSet,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
5,
&texDescriptorShadowMap),
};
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL);
// Offscreen (scene)
// Model
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.model));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vks::initializers::writeDescriptorSet(
descriptorSets.model,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
0,
&uniformBuffers.vsOffscreen.descriptor),
// Binding 1: Color map
vks::initializers::writeDescriptorSet(
descriptorSets.model,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1,
&textures.model.colorMap.descriptor),
// Binding 2: Normal map
vks::initializers::writeDescriptorSet(
descriptorSets.model,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2,
&textures.model.normalMap.descriptor)
};
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL);
// Background
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.background));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vks::initializers::writeDescriptorSet(
descriptorSets.background,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
0,
&uniformBuffers.vsOffscreen.descriptor),
// Binding 1: Color map
vks::initializers::writeDescriptorSet(
descriptorSets.background,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1,
&textures.background.colorMap.descriptor),
// Binding 2: Normal map
vks::initializers::writeDescriptorSet(
descriptorSets.background,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2,
&textures.background.normalMap.descriptor)
};
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL);
// Shadow mapping
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.shadow));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vks::initializers::writeDescriptorSet(
descriptorSets.shadow,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
0,
&uniformBuffers.uboShadowGS.descriptor),
};
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL);
}
void preparePipelines()
{
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState =
vks::initializers::pipelineInputAssemblyStateCreateInfo(
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
0,
VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState =
vks::initializers::pipelineRasterizationStateCreateInfo(
VK_POLYGON_MODE_FILL,
VK_CULL_MODE_BACK_BIT,
VK_FRONT_FACE_CLOCKWISE,
0);
VkPipelineColorBlendAttachmentState blendAttachmentState =
vks::initializers::pipelineColorBlendAttachmentState(
0xf,
VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState =
vks::initializers::pipelineColorBlendStateCreateInfo(
1,
&blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState =
vks::initializers::pipelineDepthStencilStateCreateInfo(
VK_TRUE,
VK_TRUE,
VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState =
vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineMultisampleStateCreateInfo multisampleState =
vks::initializers::pipelineMultisampleStateCreateInfo(
VK_SAMPLE_COUNT_1_BIT,
0);
std::vector<VkDynamicState> dynamicStateEnables = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamicState =
vks::initializers::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
static_cast<uint32_t>(dynamicStateEnables.size()),
0);
// Final fullscreen pass pipeline
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
shaderStages[0] = loadShader(getAssetPath() + "shaders/deferredshadows/deferred.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/deferredshadows/deferred.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
VkGraphicsPipelineCreateInfo pipelineCreateInfo =
vks::initializers::pipelineCreateInfo(
pipelineLayouts.deferred,
renderPass,
0);
pipelineCreateInfo.pVertexInputState = &vertices.inputState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pColorBlendState = &colorBlendState;
pipelineCreateInfo.pMultisampleState = &multisampleState;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pDepthStencilState = &depthStencilState;
pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCreateInfo.pStages = shaderStages.data();
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.deferred));
// Debug display pipeline
shaderStages[0] = loadShader(getAssetPath() + "shaders/deferredshadows/debug.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/deferredshadows/debug.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.debug));
// Offscreen pipeline
shaderStages[0] = loadShader(getAssetPath() + "shaders/deferredshadows/mrt.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/deferredshadows/mrt.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
// Separate render pass
pipelineCreateInfo.renderPass = frameBuffers.deferred->renderPass;
// Separate layout
pipelineCreateInfo.layout = pipelineLayouts.offscreen;
// Blend attachment states required for all color attachments
// This is important, as color write mask will otherwise be 0x0 and you
// won't see anything rendered to the attachment
std::array<VkPipelineColorBlendAttachmentState, 3> blendAttachmentStates =
{
vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE),
vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE),
vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE)
};
colorBlendState.attachmentCount = static_cast<uint32_t>(blendAttachmentStates.size());
colorBlendState.pAttachments = blendAttachmentStates.data();
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.offscreen));
// Shadow mapping pipeline
// The shadow mapping pipeline uses geometry shader instancing (invocations layout modifier) to output
// shadow maps for multiple lights sources into the different shadow map layers in one single render pass
std::array<VkPipelineShaderStageCreateInfo, 2> shadowStages;
shadowStages[0] = loadShader(getAssetPath() + "shaders/deferredshadows/shadow.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shadowStages[1] = loadShader(getAssetPath() + "shaders/deferredshadows/shadow.geom.spv", VK_SHADER_STAGE_GEOMETRY_BIT);
pipelineCreateInfo.pStages = shadowStages.data();
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shadowStages.size());
// Shadow pass doesn't use any color attachments
colorBlendState.attachmentCount = 0;
colorBlendState.pAttachments = nullptr;
// Cull front faces
rasterizationState.cullMode = VK_CULL_MODE_FRONT_BIT;
depthStencilState.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
// Enable depth bias
rasterizationState.depthBiasEnable = VK_TRUE;
// Add depth bias to dynamic state, so we can change it at runtime
dynamicStateEnables.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
dynamicState =
vks::initializers::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
static_cast<uint32_t>(dynamicStateEnables.size()),
0);
// Reset blend attachment state
pipelineCreateInfo.renderPass = frameBuffers.shadow->renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.shadowpass));
}
// Prepare and initialize uniform buffer containing shader uniforms
void prepareUniformBuffers()
{
// Fullscreen vertex shader
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffers.vsFullScreen,
sizeof(uboVS)));