-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathMeshRenderer.cpp
More file actions
1706 lines (1389 loc) · 66.2 KB
/
MeshRenderer.cpp
File metadata and controls
1706 lines (1389 loc) · 66.2 KB
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
//=================================================================================================
//
// Shadows Sample
// by MJP
// http://mynameismjp.wordpress.com/
//
// All code licensed under the MIT license
//
//=================================================================================================
#include "PCH.h"
#include "MeshRenderer.h"
#include "AppSettings.h"
#include "SharedConstants.h"
#include "SampleFramework11/Exceptions.h"
#include "SampleFramework11/Utility.h"
#include "SampleFramework11/ShaderCompilation.h"
#include "SampleFramework11/App.h"
#include "SampleFramework11/Profiler.h"
#include "SampleFramework11/Settings.h"
// Constants
static const float ShadowNearClip = 1.0f;
static const bool UseComputeReduction = true;
// Finds the approximate smallest enclosing bounding sphere for a set of points. Based on
// "An Efficient Bounding Sphere", by Jack Ritter.
static Sphere ComputeBoundingSphereFromPoints(const XMFLOAT3* points, uint32 numPoints, uint32 stride)
{
Sphere sphere;
Assert_(numPoints > 0);
Assert_(points);
// Find the points with minimum and maximum x, y, and z
XMVECTOR MinX, MaxX, MinY, MaxY, MinZ, MaxZ;
MinX = MaxX = MinY = MaxY = MinZ = MaxZ = XMLoadFloat3(points);
for(uint32 i = 1; i < numPoints; i++)
{
XMVECTOR Point = XMLoadFloat3((XMFLOAT3*)((BYTE*)points + i * stride));
float px = XMVectorGetX(Point);
float py = XMVectorGetY(Point);
float pz = XMVectorGetZ(Point);
if(px < XMVectorGetX(MinX))
MinX = Point;
if(px > XMVectorGetX(MaxX))
MaxX = Point;
if(py < XMVectorGetY(MinY))
MinY = Point;
if(py > XMVectorGetY(MaxY))
MaxY = Point;
if(pz < XMVectorGetZ(MinZ))
MinZ = Point;
if(pz > XMVectorGetZ(MaxZ))
MaxZ = Point;
}
// Use the min/max pair that are farthest apart to form the initial sphere.
XMVECTOR DeltaX = MaxX - MinX;
XMVECTOR DistX = XMVector3Length(DeltaX);
XMVECTOR DeltaY = MaxY - MinY;
XMVECTOR DistY = XMVector3Length(DeltaY);
XMVECTOR DeltaZ = MaxZ - MinZ;
XMVECTOR DistZ = XMVector3Length(DeltaZ);
XMVECTOR Center;
XMVECTOR Radius;
if(XMVector3Greater(DistX, DistY))
{
if(XMVector3Greater(DistX, DistZ))
{
// Use min/max x.
Center = (MaxX + MinX) * 0.5f;
Radius = DistX * 0.5f;
}
else
{
// Use min/max z.
Center = (MaxZ + MinZ) * 0.5f;
Radius = DistZ * 0.5f;
}
}
else // Y >= X
{
if(XMVector3Greater(DistY, DistZ))
{
// Use min/max y.
Center = (MaxY + MinY) * 0.5f;
Radius = DistY * 0.5f;
}
else
{
// Use min/max z.
Center = (MaxZ + MinZ) * 0.5f;
Radius = DistZ * 0.5f;
}
}
// Add any points not inside the sphere.
for(uint32 i = 0; i < numPoints; i++)
{
XMVECTOR Point = XMLoadFloat3((XMFLOAT3*)((BYTE*)points + i * stride));
XMVECTOR Delta = Point - Center;
XMVECTOR Dist = XMVector3Length(Delta);
if(XMVector3Greater(Dist, Radius))
{
// Adjust sphere to include the new point.
Radius = (Radius + Dist) * 0.5f;
Center += (XMVectorReplicate(1.0f) - Radius * XMVectorReciprocal(Dist)) * Delta;
}
}
XMStoreFloat3(&sphere.Center, Center);
XMStoreFloat(&sphere.Radius, Radius);
return sphere;
}
// Calculates the inverse a camera's view * projection matrices
static Float4x4 CalculateInverseViewProj(const Camera& camera)
{
Float4x4 invView = camera.WorldMatrix();
Float4x4 invProj = Float4x4::Invert(camera.ProjectionMatrix());
return invProj * invView;
}
// Calculates the frustum planes given a camera
static void ComputeFrustum(const Camera& camera, Frustum& frustum)
{
XMMATRIX invViewProj = CalculateInverseViewProj(camera).ToSIMD();
// Corners in homogeneous clip space
XMVECTOR corners[8] =
{ // 7--------6
XMVectorSet( 1.0f, -1.0f, 0.0f, 1.0f), // /| /|
XMVectorSet(-1.0f, -1.0f, 0.0f, 1.0f), // Y ^ / | / |
XMVectorSet( 1.0f, 1.0f, 0.0f, 1.0f), // | _ 3--------2 |
XMVectorSet(-1.0f, 1.0f, 0.0f, 1.0f), // | /' Z | | | |
XMVectorSet( 1.0f, -1.0f, 1.0f, 1.0f), // |/ | 5-----|--4
XMVectorSet(-1.0f, -1.0f, 1.0f, 1.0f), // + ---> X | / | /
XMVectorSet( 1.0f, 1.0f, 1.0f, 1.0f), // |/ |/
XMVectorSet(-1.0f, 1.0f, 1.0f, 1.0f), // 1--------0
};
// Convert to world space
for(uint32 i = 0; i < 8; ++i)
corners[i] = XMVector3TransformCoord(corners[i], invViewProj);
// Calculate the 6 planes
frustum.Planes[0] = XMPlaneFromPoints(corners[0], corners[4], corners[2]);
frustum.Planes[1] = XMPlaneFromPoints(corners[1], corners[3], corners[5]);
frustum.Planes[2] = XMPlaneFromPoints(corners[3], corners[2], corners[7]);
frustum.Planes[3] = XMPlaneFromPoints(corners[1], corners[5], corners[0]);
frustum.Planes[4] = XMPlaneFromPoints(corners[5], corners[7], corners[4]);
frustum.Planes[5] = XMPlaneFromPoints(corners[1], corners[0], corners[3]);
}
// Tests a frustum for intersection with a sphere
static uint32 TestFrustumSphere(const Frustum& frustum, const Sphere& sphere, bool ignoreNearZ)
{
XMVECTOR sphereCenter = XMLoadFloat3(&sphere.Center);
uint32 result = 1;
uint32 numPlanes = ignoreNearZ ? 5 : 6;
for(uint32 i = 0; i < numPlanes; i++) {
float distance = XMVectorGetX(XMPlaneDotCoord(frustum.Planes[i], sphereCenter));
if (distance < -sphere.Radius)
return 0;
else if (distance < sphere.Radius)
result = 1;
}
return result;
}
// Calculates the bounding sphere for each MeshPart
static void ComputeBoundingSpheres(ID3D11Device* device, ID3D11DeviceContext* context,
const Float4x4& world, Model* model,
std::vector<Sphere>& boundingSpheres)
{
boundingSpheres.clear();
for(uint32 meshIdx = 0; meshIdx < model->Meshes().size(); ++meshIdx)
{
Mesh& mesh = model->Meshes()[meshIdx];
// Create staging buffers for copying the vertex/index data to
ID3D11BufferPtr stagingVB;
ID3D11BufferPtr stagingIB;
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.BindFlags = 0;
bufferDesc.ByteWidth = mesh.NumVertices() * mesh.VertexStride();
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
bufferDesc.Usage = D3D11_USAGE_STAGING;
DXCall(device->CreateBuffer(&bufferDesc, nullptr, &stagingVB));
uint32 indexSize = mesh.IndexBufferType() == Mesh::Index16Bit ? 2 : 4;
bufferDesc.ByteWidth = mesh.NumIndices() * indexSize;
DXCall(device->CreateBuffer(&bufferDesc, nullptr, &stagingIB));
context->CopyResource(stagingVB, mesh.VertexBuffer());
context->CopyResource(stagingIB, mesh.IndexBuffer());
D3D11_MAPPED_SUBRESOURCE mapped;
context->Map(stagingVB, 0, D3D11_MAP_READ, 0, &mapped);
const BYTE* verts = reinterpret_cast<const BYTE*>(mapped.pData);
uint32 stride = mesh.VertexStride();
context->Map(stagingIB, 0, D3D11_MAP_READ, 0, &mapped);
const BYTE* indices = reinterpret_cast<const BYTE*>(mapped.pData);
const uint32* indices32 = reinterpret_cast<const uint32*>(mapped.pData);
const WORD* indices16 = reinterpret_cast<const WORD*>(mapped.pData);
for(uint32 partIdx = 0; partIdx < mesh.MeshParts().size(); ++partIdx)
{
const MeshPart& part = mesh.MeshParts()[partIdx];
std::vector<Float3> points;
for(uint32 i = 0; i < part.IndexCount; ++i)
{
uint32 index = indexSize == 2 ? indices16[part.IndexStart + i] : indices32[part.IndexStart + i];
Float3 point = *reinterpret_cast<const Float3*>(verts + (index * stride));
point = Float3::Transform(point, world);
points.push_back(point);
}
Sphere sphere = ComputeBoundingSphereFromPoints(&points[0], static_cast<uint32>(points.size()), sizeof(XMFLOAT3));
boundingSpheres.push_back(sphere);
}
context->Unmap(stagingVB, 0);
context->Unmap(stagingIB, 0);
}
}
// Makes the "global" shadow matrix used as the reference point for the cascades
static Float4x4 MakeGlobalShadowMatrix(const Camera& camera)
{
// Get the 8 points of the view frustum in world space
Float3 frustumCorners[8] =
{
Float3(-1.0f, 1.0f, 0.0f),
Float3( 1.0f, 1.0f, 0.0f),
Float3( 1.0f, -1.0f, 0.0f),
Float3(-1.0f, -1.0f, 0.0f),
Float3(-1.0f, 1.0f, 1.0f),
Float3( 1.0f, 1.0f, 1.0f),
Float3( 1.0f, -1.0f, 1.0f),
Float3(-1.0f, -1.0f, 1.0f),
};
Float4x4 invViewProj = CalculateInverseViewProj(camera);
Float3 frustumCenter = 0.0f;
for(uint64 i = 0; i < 8; ++i)
{
frustumCorners[i] = Float3::Transform(frustumCorners[i], invViewProj);
frustumCenter += frustumCorners[i];
}
frustumCenter /= 8.0f;
// Pick the up vector to use for the light camera
Float3 upDir = Float3(0.0f, 1.0f, 0.0f);
// Create a temporary view matrix for the light
Float3 lightCameraPos = frustumCenter;
Float3 lookAt = frustumCenter - AppSettings::LightDirection;
Float4x4 lightView = XMMatrixLookAtLH(lightCameraPos.ToSIMD(), lookAt.ToSIMD(), upDir.ToSIMD());
// Get position of the shadow camera
Float3 shadowCameraPos = frustumCenter + AppSettings::LightDirection.Value() * -0.5f;
// Come up with a new orthographic camera for the shadow caster
OrthographicCamera shadowCamera(-0.5f, -0.5f, 0.5f,
0.5f, 0.0f, 1.0f);
shadowCamera.SetLookAt(shadowCameraPos, frustumCenter, upDir);
Float4x4 texScaleBias = Float4x4::ScaleMatrix(Float3(0.5f, -0.5f, 1.0f));
texScaleBias.SetTranslation(Float3(0.5f, 0.5f, 0.0f));
return shadowCamera.ViewProjectionMatrix() * texScaleBias;
}
MeshRenderer::MeshRenderer() : currFrame(0)
{
}
static PixelShaderPtr CompileMeshPS(ID3D11Device* device)
{
CompileOptions opts;
opts.Add("VisualizeCascades_", AppSettings::VisualizeCascades);
opts.Add("UsePlaneDepthBias_", AppSettings::UsePlaneDepthBias);
opts.Add("FilterAcrossCascades_", AppSettings::FilterAcrossCascades);
opts.Add("FilterSize_", AppSettings::FixedFilterKernelSize());
opts.Add("ShadowMode_", uint32(AppSettings::ShadowMode));
opts.Add("RandomizeOffsets_", AppSettings::RandomizeDiscOffsets);
opts.Add("SelectFromProjection_", AppSettings::CascadeSelectionMode == CascadeSelectionModes::Projection ? 1 : 0);
return CompilePSFromFile(device, L"Mesh.hlsl", "PS", "ps_5_0", opts);
}
// Loads all shaders
void MeshRenderer::LoadShaders()
{
// Load the mesh shaders
meshDepthVS = CompileVSFromFile(device, L"DepthOnly.hlsl", "VS", "vs_5_0");
meshVS = CompileVSFromFile(device, L"Mesh.hlsl", "VS", "vs_5_0");
meshPS = CompileMeshPS(device);
fullScreenVS = CompileVSFromFile(device, L"VSMConvert.hlsl", "FullScreenVS");
for(uint32 shadowMode = uint32(ShadowMode::VSM); shadowMode < uint32(ShadowMode::NumValues); ++shadowMode)
{
for(uint32 msaaMode = 0; msaaMode < uint32(ShadowMSAA::NumValues); ++msaaMode)
{
PixelShaderPtr& shader = vsmConvertPS[shadowMode - uint32(ShadowMode::VSM)][msaaMode];
CompileOptions opts;
opts.Add("ShadowMode_", shadowMode);
opts.Add("MSAASamples_", AppSettings::MSAASamples(msaaMode));
shader = CompilePSFromFile(device, L"VSMConvert.hlsl", "ConvertToVSM", "ps_5_0", opts);
}
}
for(uint32 i = 0; i <= MaxBlurRadius; ++i)
{
CompileOptions opts;
opts.Add("Horizontal_", 1);
opts.Add("Vertical_", 0);
opts.Add("SampleRadius_", i);
opts.Add("GPUSceneSubmission_", 0);
vsmBlurH[i] = CompilePSFromFile(device, L"VSMConvert.hlsl", "BlurVSM", "ps_5_0", opts);
opts.Reset();
opts.Add("Horizontal_", 0);
opts.Add("Vertical_", 1);
opts.Add("SampleRadius_", i);
opts.Add("GPUSceneSubmission_", 0);
vsmBlurV[i] = CompilePSFromFile(device, L"VSMConvert.hlsl", "BlurVSM", "ps_5_0", opts);
}
CompileOptions opts;
opts.Add("Horizontal_", 1);
opts.Add("Vertical_", 0);
opts.Add("GPUSceneSubmission_", 1);
vsmBlurGPUH = CompilePSFromFile(device, L"VSMConvert.hlsl", "BlurVSM", "ps_5_0", opts);
opts.Reset();
opts.Add("Horizontal_", 0);
opts.Add("Vertical_", 1);
opts.Add("GPUSceneSubmission_", 1);
vsmBlurGPUV = CompilePSFromFile(device, L"VSMConvert.hlsl", "BlurVSM", "ps_5_0", opts);
depthReductionInitialPS = CompilePSFromFile(device, L"DepthReduction.hlsl", "DepthReductionInitialPS");
depthReductionPS = CompilePSFromFile(device, L"DepthReduction.hlsl", "DepthReductionPS");
opts.Reset();
opts.Add("CS_", 1);
depthReductionInitialCS = CompileCSFromFile(device, L"DepthReduction.hlsl", "DepthReductionInitialCS",
"cs_5_0", opts);
depthReductionCS = CompileCSFromFile(device, L"DepthReduction.hlsl", "DepthReductionCS",
"cs_5_0", opts);
clearArgsBuffer = CompileCSFromFile(device, L"GPUBatch.hlsl", "ClearArgsBuffer");
cullDrawCalls = CompileCSFromFile(device, L"GPUBatch.hlsl", "CullDrawCalls");
batchDrawCalls = CompileCSFromFile(device, L"GPUBatch.hlsl", "BatchDrawCalls");
setupCascades = CompileCSFromFile(device, L"SetupShadows.hlsl", "SetupCascades");
drawFrustumVS = CompileVSFromFile(device, L"DrawFrustum.hlsl", "VSMain");
drawFrustumPS = CompilePSFromFile(device, L"DrawFrustum.hlsl", "PSMain");
}
// Creates shadow map render targets and depth targets
void MeshRenderer::CreateShadowMaps()
{
// Create the shadow map as a texture atlas
const uint32 ShadowMapSize = AppSettings::ShadowMapResolution();
DXGI_FORMAT depthFormat = DXGI_FORMAT_D32_FLOAT;
if(AppSettings::DepthBufferFormat == DepthBufferFormats::DB16Unorm)
depthFormat = DXGI_FORMAT_D16_UNORM;
else if(AppSettings::DepthBufferFormat == DepthBufferFormats::DB24Unorm)
depthFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
if(AppSettings::UseFilterableShadows())
{
uint32 msaaSamples = AppSettings::MSAASamples();
shadowMap.Initialize(device, ShadowMapSize, ShadowMapSize, depthFormat, true, msaaSamples, 0, 1);
DXGI_FORMAT smFmt;
if(AppSettings::ShadowMode == ShadowMode::EVSM4)
{
if(AppSettings::SMFormat == SMFormat::SM16Bit)
smFmt = DXGI_FORMAT_R16G16B16A16_FLOAT;
else
smFmt = DXGI_FORMAT_R32G32B32A32_FLOAT;
}
else if(AppSettings::ShadowMode == ShadowMode::EVSM2)
{
if(AppSettings::SMFormat == SMFormat::SM16Bit)
smFmt = DXGI_FORMAT_R16G16_FLOAT;
else
smFmt = DXGI_FORMAT_R32G32_FLOAT;
}
else if(AppSettings::ShadowMode == ShadowMode::MSMHamburger || AppSettings::ShadowMode == ShadowMode::MSMHausdorff)
{
if(AppSettings::SMFormat == SMFormat::SM16Bit)
smFmt = DXGI_FORMAT_R16G16B16A16_UNORM;
else
smFmt = DXGI_FORMAT_R32G32B32A32_FLOAT;
}
else
{
if(AppSettings::SMFormat == SMFormat::SM16Bit)
smFmt = DXGI_FORMAT_R16G16_UNORM;
else
smFmt = DXGI_FORMAT_R32G32_FLOAT;
}
uint32 numMips = AppSettings::EnableShadowMips ? 0 : 1;
varianceShadowMap.Initialize(device, ShadowMapSize, ShadowMapSize, smFmt, numMips, 1, 0,
AppSettings::EnableShadowMips, false, NumCascades, false);
tempVSM.Initialize(device, ShadowMapSize, ShadowMapSize, smFmt, 1, 1, 0, false, false, 1, false);
}
else
{
shadowMap.Initialize(device, ShadowMapSize, ShadowMapSize, depthFormat, true, 1, 0, NumCascades);
varianceShadowMap = RenderTarget2D();
}
for(uint32 cascadeIdx = 0; cascadeIdx < NumCascades; ++cascadeIdx)
{
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = { };
shadowMap.SRView->GetDesc(&srvDesc);
srvDesc.Texture2DArray.ArraySize = 1;
srvDesc.Texture2DArray.FirstArraySlice = cascadeIdx;
device->CreateShaderResourceView(shadowMap.Texture, &srvDesc, &cascadeSlices[cascadeIdx]);
}
}
// Creates bounding spheres for a mesh, and creates resources used for GPU batching
static void SetupMesh(ID3D11Device* device, ID3D11DeviceContext* context, Model* model,
MeshData& meshData, const Float4x4& world, VertexShaderPtr meshVS,
VertexShaderPtr meshDepthVS)
{
meshData.Model = model;
ComputeBoundingSpheres(device, context, world, model, meshData.BoundingSpheres);
std::vector<Float3> positions;
std::vector<uint32> indices;
std::vector<DrawCall> drawCalls;
uint64 drawIdx = 0;
for(uint64 meshIdx = 0; meshIdx < model->Meshes().size(); ++meshIdx)
{
const Mesh& mesh = model->Meshes()[meshIdx];
const uint8* verts = mesh.Vertices();
const uint32 vtxOffset = uint32(positions.size());
for(uint64 i = 0; i < mesh.NumVertices(); ++i)
{
positions.push_back(*reinterpret_cast<const Float3*>(verts));
verts += mesh.VertexStride();
}
const uint32 idxOffset = uint32(indices.size());
for(uint32 i = 0; i < mesh.NumIndices(); ++i)
{
uint32 idx = GetIndex(mesh.Indices(), i, mesh.IndexSize());
idx += vtxOffset;
indices.push_back(idx);
}
for(uint64 partIdx = 0; partIdx < mesh.MeshParts().size(); ++partIdx)
{
const MeshPart& part = mesh.MeshParts()[partIdx];
DrawCall drawCall;
drawCall.StartIndex = part.IndexStart + idxOffset;
drawCall.NumIndices = part.IndexCount;
drawCall.SphereCenter = meshData.BoundingSpheres[drawIdx].Center;
drawCall.SphereRadius= meshData.BoundingSpheres[drawIdx].Radius;
drawCalls.push_back(drawCall);
++drawIdx;
}
}
meshData.Indices.Initialize(device, sizeof(uint32), uint32(indices.size()), false, false, false, indices.data());
meshData.CulledIndices.Initialize(device, DXGI_FORMAT_R32_UINT, 4, uint32(indices.size()), false, false, true);
meshData.DrawCalls.Initialize(device, sizeof(DrawCall), uint32(drawCalls.size()), false, false, false, drawCalls.data());
meshData.CulledDraws.Initialize(device, sizeof(CulledDraw), uint32(drawCalls.size()), true, true, false, nullptr);
D3D11_BUFFER_DESC vbDesc;
vbDesc.Usage = D3D11_USAGE_IMMUTABLE;
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbDesc.ByteWidth = uint32(positions.size() * sizeof(Float3));
vbDesc.CPUAccessFlags = 0;
vbDesc.MiscFlags = 0;
vbDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA vbInitData = { positions.data(), 0, 0 };
DXCall(device->CreateBuffer(&vbDesc, &vbInitData, &meshData.PositionsVB));
meshData.InputLayouts.clear();
meshData.DepthInputLayouts.clear();
for(uint32 i = 0; i < model->Meshes().size(); ++i)
{
Mesh& mesh = model->Meshes()[i];
ID3D11InputLayoutPtr inputLayout;
DXCall(device->CreateInputLayout(mesh.InputElements(), mesh.NumInputElements(),
meshVS->ByteCode->GetBufferPointer(),
meshVS->ByteCode->GetBufferSize(), &inputLayout));
meshData.InputLayouts.push_back(inputLayout);
DXCall(device->CreateInputLayout(mesh.InputElements(), mesh.NumInputElements(),
meshDepthVS->ByteCode->GetBufferPointer(),
meshDepthVS->ByteCode->GetBufferSize(), &inputLayout));
meshData.DepthInputLayouts.push_back(inputLayout);
}
}
void MeshRenderer::SetSceneMesh(ID3D11DeviceContext* context, Model* model, const Float4x4& world)
{
SetupMesh(device, context, model, scene, world, meshVS, meshDepthVS);
}
void MeshRenderer::SetCharacterMesh(ID3D11DeviceContext* context, Model* model, const Float4x4& world)
{
SetupMesh(device, context, model, character, world, meshVS, meshDepthVS);
}
// Loads resources
void MeshRenderer::Initialize(ID3D11Device* device, ID3D11DeviceContext* context)
{
this->device = device;
blendStates.Initialize(device);
rasterizerStates.Initialize(device);
depthStencilStates.Initialize(device);
samplerStates.Initialize(device);
depthOnlyConstants.Initialize(device, true);
meshVSConstants.Initialize(device);
meshPSConstants.Initialize(device, true);
vsmConstants.Initialize(device, true);
reductionConstants.Initialize(device);
gpuBatchConstants.Initialize(device, true);
shadowSetupConstants.Initialize(device);
tempViewProjBuffer.Initialize(device);
tempFrustumPlanesBuffer.Initialize(device);
drawFrustumConstants.Initialize(device);
defaultTexture = LoadTexture(device, L"..\\Content\\Textures\\Default.dds");
LoadShaders();
D3D11_RASTERIZER_DESC rsDesc = RasterizerStates::NoCullDesc();
rsDesc.DepthClipEnable = FALSE;
DXCall(device->CreateRasterizerState(&rsDesc, &shadowRSState));
for(uint32 anisotropy = 0; anisotropy < uint32(ShadowAnisotropy::NumValues); ++anisotropy)
{
D3D11_SAMPLER_DESC sampDesc = SamplerStates::AnisotropicDesc();
sampDesc.MaxAnisotropy = AppSettings::NumAnisotropicSamples(anisotropy);
DXCall(device->CreateSamplerState(&sampDesc, &evsmSamplers[anisotropy]));
}
// Initialize a 64x64 texture containing random rotation values
static const uint32 RandomTextureSize = 64;
BYTE randomValues[RandomTextureSize * RandomTextureSize];
srand(0);
for(uint32 i = 0; i < RandomTextureSize * RandomTextureSize; ++i)
randomValues[i] = static_cast<BYTE>(RandFloat() * 255.0f);
D3D11_TEXTURE2D_DESC texDesc = { };
texDesc.Width = RandomTextureSize;
texDesc.Height = RandomTextureSize;
texDesc.Format = DXGI_FORMAT_R8_UNORM;
texDesc.ArraySize = 1;
texDesc.MipLevels = 1;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.Usage = D3D11_USAGE_IMMUTABLE;
texDesc.MiscFlags = 0;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA initData = { };
initData.pSysMem = randomValues;
initData.SysMemPitch = RandomTextureSize;
initData.SysMemSlicePitch = 0;
ID3D11Texture2DPtr randomValuesTexture;
DXCall(device->CreateTexture2D(&texDesc, &initData, &randomValuesTexture));
DXCall(device->CreateShaderResourceView(randomValuesTexture, nullptr, &randomRotations));
// Create the staging textures for reading back the reduced depth buffer
for(uint32 i = 0; i < MaxReadbackLatency; ++i)
reductionStagingTextures[i].Initialize(device, 1, 1, DXGI_FORMAT_R16G16_UNORM);
// Create resources needed for GPU draw call batching
uint32 drawArgsInit[5] = { 0, 1, 0, 0, 0 };
drawArgsBuffer.Initialize(device, DXGI_FORMAT_R32_TYPELESS, 4, 5, true, false, false, true, drawArgsInit);
uint32 dispatchArgsInit[4] = { 1, 1, 1, 0 };
batchDispatchArgs.Initialize(device, DXGI_FORMAT_R32_TYPELESS, 4, 4, true, false, false, true, dispatchArgsInit);
D3D11_INPUT_ELEMENT_DESC inputElements[1] = { };
inputElements[0].AlignedByteOffset = 0;
inputElements[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
inputElements[0].InputSlot = 0;
inputElements[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
inputElements[0].InstanceDataStepRate = 0;
inputElements[0].SemanticName = "POSITION";
inputElements[0].SemanticIndex = 0;
DXCall(device->CreateInputLayout(inputElements, 1, meshDepthVS->ByteCode->GetBufferPointer(),
meshDepthVS->ByteCode->GetBufferSize(), &depthGPUInputLayout));
// Create resources for GPU cascade setup
cascadeMatrixBuffer.Initialize(device, sizeof(Float4), NumCascades * 4, true);
cascadeSplitBuffer.Initialize(device, sizeof(float), NumCascades, true);
cascadeOffsetBuffer.Initialize(device, sizeof(Float4), NumCascades, true);
cascadeScaleBuffer.Initialize(device, sizeof(Float4), NumCascades, true);
cascadePlanesBuffer.Initialize(device, sizeof(Float4), NumCascades * 6, true);
{
const uint16 frustumIndices[] =
{
0, 1,
1, 3,
3, 2,
2, 0,
0, 4,
1, 5,
2, 6,
3, 7,
4, 5,
5, 7,
7, 6,
6, 4,
};
D3D11_BUFFER_DESC ibDesc = { };
ibDesc.ByteWidth = sizeof(frustumIndices);
ibDesc.Usage = D3D11_USAGE_IMMUTABLE;
ibDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibDesc.CPUAccessFlags = 0;
ibDesc.MiscFlags = 0;
ibDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA subResData = { };
subResData.pSysMem = frustumIndices;
DXCall(device->CreateBuffer(&ibDesc, &subResData, &frustumLineIB));
frustumLineIndexCount = ArraySize_(frustumIndices);
}
CreateShadowMaps();
}
// Performs frustum/sphere intersection tests for all MeshPart's
static void DoFrustumTests(const Camera& camera, bool ignoreNearZ, MeshData& mesh)
{
mesh.FrustumTests.clear();
mesh.NumSuccessfulTests = 0;
Frustum frustum;
ComputeFrustum(camera, frustum);
for(uint32 i = 0; i < mesh.BoundingSpheres.size(); ++i)
{
const Sphere& sphere = mesh.BoundingSpheres[i];
uint32 test = TestFrustumSphere(frustum, sphere, ignoreNearZ);
mesh.FrustumTests.push_back(test);
mesh.NumSuccessfulTests += test;
}
}
void MeshRenderer::Update()
{
if(AppSettings::ShadowMapSize.Changed() || AppSettings::ShadowMode.Changed()
|| AppSettings::ShadowMSAA.Changed() || AppSettings::SMFormat.Changed()
|| AppSettings::EnableShadowMips.Changed() || AppSettings::DepthBufferFormat.Changed())
CreateShadowMaps();
if(AppSettings::VisualizeCascades.Changed() || AppSettings::UsePlaneDepthBias.Changed()
|| AppSettings::FilterAcrossCascades.Changed() || AppSettings::FixedFilterSize.Changed()
|| AppSettings::ShadowMode.Changed() || AppSettings::RandomizeDiscOffsets.Changed()
|| AppSettings::CascadeSelectionMode.Changed())
meshPS = CompileMeshPS(device);
if(AppSettings::AutoComputeDepthBounds && AppSettings::GPUSceneSubmission == false)
{
AppSettings::MinCascadeDistance.SetValue(reductionDepth.x);
AppSettings::MaxCascadeDistance.SetValue(reductionDepth.y);
}
else
currFrame = 0;
}
// Creates the chain of render targets used for computing min/max depth
void MeshRenderer::CreateReductionTargets(uint32 width, uint32 height)
{
depthReductionTargets.clear();
if(UseComputeReduction)
{
uint32 w = width;
uint32 h = height;
while(w > 1 || h > 1)
{
w = DispatchSize(ReductionTGSize, w);
h = DispatchSize(ReductionTGSize, h);
RenderTarget2D rt;
rt.Initialize(device, w, h, DXGI_FORMAT_R16G16_UNORM, 1, 1, 0, FALSE, TRUE);
depthReductionTargets.push_back(rt);
}
}
else
{
// Basically create a mip chain
uint32 w = width;
uint32 h = height;
while(w > 1 || h > 1)
{
w = static_cast<uint32>(Round(w / 2.0f));
h = static_cast<uint32>(Round(h / 2.0f));
w = std::max<uint32>(w, 1);
h = std::max<uint32>(h, 1);
RenderTarget2D rt;
rt.Initialize(device, w, h, DXGI_FORMAT_R16G16_UNORM);
depthReductionTargets.push_back(rt);
}
}
}
// Computes the min and max depth from the depth buffer using a parallel reduction
void MeshRenderer::ReduceDepth(ID3D11DeviceContext* context, ID3D11ShaderResourceView* depthTarget,
const Camera& camera)
{
PIXEvent event(L"Depth Reduction");
ProfileBlock block(L"Depth Reduction");
reductionConstants.Data.Projection = Float4x4::Transpose(camera.ProjectionMatrix());
reductionConstants.Data.NearClip = camera.NearClip();
reductionConstants.Data.FarClip = camera.FarClip();
reductionConstants.ApplyChanges(context);
if(UseComputeReduction)
{
reductionConstants.SetCS(context, 0);
ID3D11RenderTargetView* rtvs[1] = { nullptr };
context->OMSetRenderTargets(1, rtvs, nullptr);
ID3D11UnorderedAccessView* uavs[1] = { depthReductionTargets[0].UAView };
context->CSSetUnorderedAccessViews(0, 1, uavs, nullptr);
ID3D11ShaderResourceView* srvs[1] = { depthTarget };
context->CSSetShaderResources(0, 1, srvs);
ID3D11SamplerState* samplers[1] = { samplerStates.LinearClamp() };
context->CSSetSamplers(0, 1, samplers);
context->CSSetShader(depthReductionInitialCS, nullptr, 0);
uint32 dispatchX = depthReductionTargets[0].Width;
uint32 dispatchY = depthReductionTargets[0].Height;
context->Dispatch(dispatchX, dispatchY, 1);
uavs[0] = nullptr;
context->CSSetUnorderedAccessViews(0, 1, uavs, nullptr);
srvs[0] = nullptr;
context->CSSetShaderResources(0, 1, srvs);
context->CSSetShader(depthReductionCS, nullptr, 0);
for(uint32 i = 1; i < depthReductionTargets.size(); ++i)
{
uavs[0] = depthReductionTargets[i].UAView;
context->CSSetUnorderedAccessViews(0, 1, uavs, nullptr);
srvs[0] = depthReductionTargets[i - 1].SRView;
context->CSSetShaderResources(0, 1, srvs);
dispatchX = depthReductionTargets[i].Width;
dispatchY = depthReductionTargets[i].Height;
context->Dispatch(dispatchX, dispatchY, 1);
uavs[0] = nullptr;
context->CSSetUnorderedAccessViews(0, 1, uavs, nullptr);
srvs[0] = nullptr;
context->CSSetShaderResources(0, 1, srvs);
}
}
else
{
float blendFactor[4] = {1, 1, 1, 1};
context->OMSetBlendState(blendStates.BlendDisabled(), blendFactor, 0xFFFFFFFF);
context->RSSetState(rasterizerStates.NoCull());
context->OMSetDepthStencilState(depthStencilStates.DepthDisabled(), 0);
ID3D11Buffer* vbs[1] = { nullptr };
uint32 strides[1] = { 0 };
uint32 offsets[1] = { 0 };
context->IASetVertexBuffers(0, 1, vbs, strides, offsets);
context->IASetIndexBuffer(nullptr, DXGI_FORMAT_R32_UINT, 0);
context->IASetInputLayout(nullptr);
reductionConstants.SetPS(context, 0);
context->VSSetShader(fullScreenVS, nullptr, 0);
context->PSSetShader(depthReductionInitialPS, nullptr, 0);
ID3D11RenderTargetView* rtvs[1] = { depthReductionTargets[0].RTView };
context->OMSetRenderTargets(1, rtvs, nullptr);
ID3D11ShaderResourceView* srvs[1] = { depthTarget };
context->PSSetShaderResources(0, 1, srvs);
ID3D11SamplerState* samplers[1] = { samplerStates.LinearClamp() };
context->PSSetSamplers(0, 1, samplers);
D3D11_VIEWPORT vp;
vp.TopLeftX = 0.0f;
vp.TopLeftY = 0.0f;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.Width = static_cast<float>(depthReductionTargets[0].Width);
vp.Height = static_cast<float>(depthReductionTargets[0].Height);
context->RSSetViewports(1, &vp);
context->Draw(3, 0);
srvs[0] = nullptr;
context->PSSetShaderResources(0, 1, srvs);
context->PSSetShader(depthReductionPS, nullptr, 0);
for(uint32 i = 1; i < depthReductionTargets.size(); ++i)
{
rtvs[0] = depthReductionTargets[i].RTView;
context->OMSetRenderTargets(1, rtvs, nullptr);
srvs[0] = depthReductionTargets[i - 1].SRView;
context->PSSetShaderResources(0, 1, srvs);
vp.Width = static_cast<float>(depthReductionTargets[i].Width);
vp.Height = static_cast<float>(depthReductionTargets[i].Height);
context->RSSetViewports(1, &vp);
context->Draw(3, 0);
srvs[0] = nullptr;
context->PSSetShaderResources(0, 1, srvs);
}
}
// Don't read back the depth when doing GPU batching, because that would default the purpose!
if(AppSettings::GPUSceneSubmission)
return;
// Copy to a staging texture
const uint32 latency = uint32(AppSettings::ReadbackLatency + 1);
ID3D11Texture2D* lastTarget = depthReductionTargets[depthReductionTargets.size() - 1].Texture;
context->CopyResource(reductionStagingTextures[currFrame % latency].Texture, lastTarget);
++currFrame;
if(currFrame >= latency)
{
CPUProfileBlock cpuBlock(L"Depth Readback");
StagingTexture2D& stagingTexture = reductionStagingTextures[currFrame % latency];
uint32 pitch;
const uint16* texData = reinterpret_cast<uint16*>(stagingTexture.Map(context, 0, pitch));
reductionDepth.x = texData[0] / static_cast<float>(0xffff);
reductionDepth.y = texData[1] / static_cast<float>(0xffff);
stagingTexture.Unmap(context, 0);
}
else
{
reductionDepth = Float2(0.0f, 1.0f);
}
}
// Convert to a VSM map
void MeshRenderer::ConvertToVSM(ID3D11DeviceContext* context, uint32 cascadeIdx,
Float3 cascadeScale, Float3 cascade0Scale)
{
PIXEvent event(L"VSM Conversion");
float blendFactor[4] = {1, 1, 1, 1};
context->OMSetBlendState(blendStates.BlendDisabled(), blendFactor, 0xFFFFFFFF);
context->RSSetState(rasterizerStates.NoCull());
context->OMSetDepthStencilState(depthStencilStates.DepthDisabled(), 0);
ID3D11Buffer* vbs[1] = { nullptr };
uint32 strides[1] = { 0 };
uint32 offsets[1] = { 0 };
context->IASetVertexBuffers(0, 1, vbs, strides, offsets);
context->IASetIndexBuffer(nullptr, DXGI_FORMAT_R32_UINT, 0);
context->IASetInputLayout(nullptr);
D3D11_VIEWPORT vp;
vp.TopLeftX = 0.0f;
vp.TopLeftY = 0.0f;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.Width = static_cast<float>(varianceShadowMap.Width);
vp.Height = static_cast<float>(varianceShadowMap.Height);
context->RSSetViewports(1, &vp);
vsmConstants.Data.CascadeScale = Float4(cascadeScale, 1.0f);
vsmConstants.Data.Cascade0Scale = Float4(cascade0Scale, 1.0f);
vsmConstants.Data.ShadowMapSize = Float2(float(varianceShadowMap.Width), float(varianceShadowMap.Height));
vsmConstants.ApplyChanges(context);
vsmConstants.SetPS(context, 0);
if(AppSettings::GPUSceneSubmission)
{
// Copy the cascade scale from the GPU buffer
CopyBufferRegion(context, vsmConstants.Buffer, cascadeScaleBuffer.Buffer, 0,
sizeof(Float4) * cascadeIdx, sizeof(vsmConstants.Data.CascadeScale));
CopyBufferRegion(context, vsmConstants.Buffer, cascadeScaleBuffer.Buffer, sizeof(Float4),
sizeof(Float4) * 0, sizeof(vsmConstants.Data.CascadeScale));
}
context->VSSetShader(fullScreenVS, nullptr, 0);
ID3D11PixelShader* ps = vsmConvertPS[AppSettings::ShadowMode - uint32(ShadowMode::VSM)][AppSettings::ShadowMSAA];
context->PSSetShader(ps, nullptr, 0);
ID3D11RenderTargetView* rtvs[1] = { varianceShadowMap.RTVArraySlices[cascadeIdx] };
context->OMSetRenderTargets(1, rtvs, nullptr);
ID3D11ShaderResourceView* srvs[1] = { shadowMap.SRView };
context->PSSetShaderResources(0, 1, srvs);
context->Draw(3, 0);
srvs[0] = nullptr;
context->PSSetShaderResources(0, 1, srvs);
float maxFilterSizeU = MaxKernelSize / std::abs(cascade0Scale.x);
float maxFilterSizeV = MaxKernelSize / std::abs(cascade0Scale.y);
const float FilterSizeU = Clamp(std::min<float>(AppSettings::FilterSize, maxFilterSizeU) * std::abs(cascadeScale.x), 1.0f, MaxKernelSize);
const float FilterSizeV = Clamp(std::min<float>(AppSettings::FilterSize, maxFilterSizeV) * std::abs(cascadeScale.y), 1.0f, MaxKernelSize);
// For GPU-driven submission, we always run the blur passes and use a dynamic loop
// in the shader. For CPU submission, we figure out the minimum sample radius and
// switch shader permutations. This could also be done with GPU submission,
// by using DrawIndirect or something similar.
if((FilterSizeU > 1.0f || FilterSizeV > 1.0f) || AppSettings::GPUSceneSubmission)
{
// Horizontal pass
uint32 sampleRadiusU = static_cast<uint32>((FilterSizeU / 2) + 0.499f);