-
Notifications
You must be signed in to change notification settings - Fork 869
Expand file tree
/
Copy pathHDRenderPipeline.LightLoop.cs
More file actions
1583 lines (1343 loc) · 93.9 KB
/
HDRenderPipeline.LightLoop.cs
File metadata and controls
1583 lines (1343 loc) · 93.9 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
using System;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
namespace UnityEngine.Rendering.HighDefinition
{
public partial class HDRenderPipeline
{
private static LocalKeyword s_BigTileVolumetricLightListKeyword;
struct LightingBuffers
{
public TextureHandle sssBuffer;
public TextureHandle diffuseLightingBuffer;
public TextureHandle ambientOcclusionBuffer;
public TextureHandle ssrLightingBuffer;
public TextureHandle ssgiLightingBuffer;
public TextureHandle contactShadowsBuffer;
public TextureHandle screenspaceShadowBuffer;
}
static LightingBuffers ReadLightingBuffers(in LightingBuffers buffers, IUnsafeRenderGraphBuilder builder)
{
var result = new LightingBuffers();
// We only read those buffers because sssBuffer and diffuseLightingBuffer our just output of the lighting process, not inputs.
result.ambientOcclusionBuffer = buffers.ambientOcclusionBuffer;
builder.UseTexture(result.ambientOcclusionBuffer, AccessFlags.Read);
result.ssrLightingBuffer = buffers.ssrLightingBuffer;
builder.UseTexture(result.ssrLightingBuffer, AccessFlags.Read);
result.ssgiLightingBuffer = buffers.ssgiLightingBuffer;
builder.UseTexture(result.ssgiLightingBuffer, AccessFlags.Read);
result.contactShadowsBuffer = buffers.contactShadowsBuffer;
builder.UseTexture(result.contactShadowsBuffer, AccessFlags.Read);
result.screenspaceShadowBuffer = buffers.screenspaceShadowBuffer;
builder.UseTexture(result.screenspaceShadowBuffer, AccessFlags.Read);
return result;
}
static void BindGlobalLightingBuffers(in LightingBuffers buffers, CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, buffers.ambientOcclusionBuffer);
cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, buffers.ssrLightingBuffer);
cmd.SetGlobalTexture(HDShaderIDs._IndirectDiffuseTexture, buffers.ssgiLightingBuffer);
cmd.SetGlobalTexture(HDShaderIDs._ContactShadowTexture, buffers.contactShadowsBuffer);
cmd.SetGlobalTexture(HDShaderIDs._ScreenSpaceShadowsTexture, buffers.screenspaceShadowBuffer);
}
static void BindGlobalThicknessBuffers(TextureHandle thicknessTexture, GraphicsBuffer thicknessReindexMap, CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._ThicknessTexture, thicknessTexture);
cmd.SetGlobalBuffer(HDShaderIDs._ThicknessReindexMap, thicknessReindexMap);
}
static void BindDefaultTexturesLightingBuffers(RenderGraphDefaultResources defaultResources, CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, defaultResources.blackTextureXR);
cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, defaultResources.blackTextureXR);
cmd.SetGlobalTexture(HDShaderIDs._IndirectDiffuseTexture, defaultResources.blackTextureXR);
cmd.SetGlobalTexture(HDShaderIDs._ContactShadowTexture, defaultResources.blackUIntTextureXR);
cmd.SetGlobalTexture(HDShaderIDs._ScreenSpaceShadowsTexture, defaultResources.blackTextureXR);
}
class BuildGPULightListPassData
{
// Common
public int totalLightCount; // Regular + Env + Decal + Local Volumetric Fog
public int viewCount;
public bool runLightList;
public bool clearLightLists;
public bool enableFeatureVariants;
public bool computeMaterialVariants;
public bool computeLightVariants;
public bool skyEnabled;
public LightList lightList;
public bool canClearLightList;
public int directionalLightCount;
// Clear Light lists
public ComputeShader clearLightListCS;
public int clearLightListKernel;
// Screen Space AABBs
public ComputeShader screenSpaceAABBShader;
public int screenSpaceAABBKernel;
// Big Tile
public ComputeShader bigTilePrepassShader;
public int bigTilePrepassKernel;
public bool runBigTilePrepass;
public int numBigTilesX, numBigTilesY;
public bool supportsVolumetric;
// FPTL
public ComputeShader buildPerTileLightListShader;
public int buildPerTileLightListKernel;
public bool runFPTL;
public int numTilesFPTLX;
public int numTilesFPTLY;
public int numTilesFPTL;
// Cluster
public ComputeShader buildPerVoxelLightListShader;
public ComputeShader clearClusterAtomicIndexShader;
public int buildPerVoxelLightListKernel;
public int numTilesClusterX;
public int numTilesClusterY;
public bool clusterNeedsDepth;
// Build dispatch indirect
public ComputeShader buildMaterialFlagsShader;
public ComputeShader clearDispatchIndirectShader;
public ComputeShader buildDispatchIndirectShader;
public ShaderVariablesLightList lightListCB;
public TextureHandle depthBuffer;
public TextureHandle stencilTexture;
public TextureHandle[] gBuffer = new TextureHandle[RenderGraph.kMaxMRTCount];
public int gBufferCount;
// Buffers filled with the CPU outside of render graph.
public BufferHandle convexBoundsBuffer;
public BufferHandle AABBBoundsBuffer;
// Transient buffers that are not used outside of BuildGPULight list so they don't need to go outside the pass.
public BufferHandle globalLightListAtomic;
public BufferHandle lightVolumeDataBuffer;
public BuildGPULightListOutput output = new BuildGPULightListOutput();
}
internal struct BuildGPULightListOutput
{
// Tile
public BufferHandle lightList;
public BufferHandle tileList;
public BufferHandle tileFeatureFlags;
public BufferHandle dispatchIndirectBuffer;
// Big Tile
public BufferHandle bigTileLightList;
public BufferHandle bigTileVolumetricLightList;
// Cluster
public BufferHandle perVoxelOffset;
public BufferHandle perVoxelLightLists;
public BufferHandle perTileLogBaseTweak;
}
static void ClearLightList(BuildGPULightListPassData data, ComputeCommandBuffer cmd, GraphicsBuffer bufferToClear)
{
cmd.SetComputeBufferParam(data.clearLightListCS, data.clearLightListKernel, HDShaderIDs._LightListToClear, bufferToClear);
Vector2 countAndOffset = new Vector2Int(bufferToClear.count, 0);
int groupSize = 64;
int totalNumberOfGroupsNeeded = (bufferToClear.count + groupSize - 1) / groupSize;
const int maxAllowedGroups = 65535;
// On higher resolutions we might end up with more than 65535 group which is not allowed, so we need to to have multiple dispatches.
int i = 0;
while (totalNumberOfGroupsNeeded > 0)
{
countAndOffset.y = maxAllowedGroups * i;
cmd.SetComputeVectorParam(data.clearLightListCS, HDShaderIDs._LightListEntriesAndOffset, countAndOffset);
int currGroupCount = Math.Min(maxAllowedGroups, totalNumberOfGroupsNeeded);
cmd.DispatchCompute(data.clearLightListCS, data.clearLightListKernel, currGroupCount, 1, 1);
totalNumberOfGroupsNeeded -= currGroupCount;
i++;
}
}
static void ClearLightLists(BuildGPULightListPassData data, ComputeCommandBuffer cmd)
{
if (data.clearLightLists)
{
// Note we clear the whole content and not just the header since it is fast enough, happens only in one frame and is a bit more robust
// to changes to the inner workings of the lists.
// Also, we clear all the lists and to be resilient to changes in pipeline.
if (data.runBigTilePrepass)
{
ClearLightList(data, cmd, data.output.bigTileLightList);
if (data.supportsVolumetric)
ClearLightList(data, cmd, data.output.bigTileVolumetricLightList);
}
if (data.canClearLightList) // This can happen when we dont have a GPULight list builder and a light list instantiated.
ClearLightList(data, cmd, data.output.lightList);
ClearLightList(data, cmd, data.output.perVoxelOffset);
}
}
// generate screen-space AABBs (used for both fptl and clustered).
static void GenerateLightsScreenSpaceAABBs(BuildGPULightListPassData data, ComputeCommandBuffer cmd)
{
if (data.totalLightCount != 0)
{
using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.GenerateLightAABBs)))
{
// With XR single-pass, we have one set of light bounds per view to iterate over (bounds are in view space for each view)
cmd.SetComputeBufferParam(data.screenSpaceAABBShader, data.screenSpaceAABBKernel, HDShaderIDs.g_data, data.convexBoundsBuffer);
cmd.SetComputeBufferParam(data.screenSpaceAABBShader, data.screenSpaceAABBKernel, HDShaderIDs.g_vBoundsBuffer, data.AABBBoundsBuffer);
ConstantBuffer.Push(cmd, data.lightListCB, data.screenSpaceAABBShader, HDShaderIDs._ShaderVariablesLightList);
const int threadsPerLight = 4; // Shader: THREADS_PER_LIGHT (4)
const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64)
int groupCount = HDUtils.DivRoundUp(data.totalLightCount * threadsPerLight, threadsPerGroup);
cmd.DispatchCompute(data.screenSpaceAABBShader, data.screenSpaceAABBKernel, groupCount, data.viewCount, 1);
}
}
}
// enable coarse 2D pass on 64x64 tiles (used for both fptl and clustered).
static void BigTilePrepass(BuildGPULightListPassData data, ComputeCommandBuffer cmd)
{
if (data.runLightList && data.runBigTilePrepass)
{
cmd.SetComputeBufferParam(data.bigTilePrepassShader, data.bigTilePrepassKernel, HDShaderIDs.g_vLightList, data.output.bigTileLightList);
cmd.SetKeyword(data.bigTilePrepassShader, s_BigTileVolumetricLightListKeyword, data.supportsVolumetric);
if (data.supportsVolumetric)
cmd.SetComputeBufferParam(data.bigTilePrepassShader, data.bigTilePrepassKernel, HDShaderIDs.g_vVolumetricLightList, data.output.bigTileVolumetricLightList);
cmd.SetComputeBufferParam(data.bigTilePrepassShader, data.bigTilePrepassKernel, HDShaderIDs.g_vBoundsBuffer, data.AABBBoundsBuffer);
cmd.SetComputeBufferParam(data.bigTilePrepassShader, data.bigTilePrepassKernel, HDShaderIDs._LightVolumeData, data.lightVolumeDataBuffer);
cmd.SetComputeBufferParam(data.bigTilePrepassShader, data.bigTilePrepassKernel, HDShaderIDs.g_data, data.convexBoundsBuffer);
ConstantBuffer.Push(cmd, data.lightListCB, data.bigTilePrepassShader, HDShaderIDs._ShaderVariablesLightList);
cmd.DispatchCompute(data.bigTilePrepassShader, data.bigTilePrepassKernel, data.numBigTilesX, data.numBigTilesY, data.viewCount);
}
}
static void BuildPerTileLightList(BuildGPULightListPassData data, ref bool tileFlagsWritten, ComputeCommandBuffer cmd)
{
// optimized for opaques only
if (data.runLightList && data.runFPTL)
{
cmd.SetComputeBufferParam(data.buildPerTileLightListShader, data.buildPerTileLightListKernel, HDShaderIDs.g_vBoundsBuffer, data.AABBBoundsBuffer);
cmd.SetComputeBufferParam(data.buildPerTileLightListShader, data.buildPerTileLightListKernel, HDShaderIDs._LightVolumeData, data.lightVolumeDataBuffer);
cmd.SetComputeBufferParam(data.buildPerTileLightListShader, data.buildPerTileLightListKernel, HDShaderIDs.g_data, data.convexBoundsBuffer);
cmd.SetComputeTextureParam(data.buildPerTileLightListShader, data.buildPerTileLightListKernel, HDShaderIDs.g_depth_tex, data.depthBuffer);
cmd.SetComputeBufferParam(data.buildPerTileLightListShader, data.buildPerTileLightListKernel, HDShaderIDs.g_vLightList, data.output.lightList);
if (data.runBigTilePrepass)
cmd.SetComputeBufferParam(data.buildPerTileLightListShader, data.buildPerTileLightListKernel, HDShaderIDs.g_vBigTileLightList, data.output.bigTileLightList);
var localLightListCB = data.lightListCB;
if (data.enableFeatureVariants)
{
uint baseFeatureFlags = 0;
if (data.directionalLightCount > 0)
{
baseFeatureFlags |= (uint)LightFeatureFlags.Directional;
}
if (data.skyEnabled)
{
baseFeatureFlags |= (uint)LightFeatureFlags.Sky;
}
if (!data.computeMaterialVariants)
{
baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags;
}
localLightListCB.g_BaseFeatureFlags = baseFeatureFlags;
cmd.SetComputeBufferParam(data.buildPerTileLightListShader, data.buildPerTileLightListKernel, HDShaderIDs.g_TileFeatureFlags, data.output.tileFeatureFlags);
tileFlagsWritten = true;
}
ConstantBuffer.Push(cmd, localLightListCB, data.buildPerTileLightListShader, HDShaderIDs._ShaderVariablesLightList);
cmd.DispatchCompute(data.buildPerTileLightListShader, data.buildPerTileLightListKernel, data.numTilesFPTLX, data.numTilesFPTLY, data.viewCount);
}
}
static void VoxelLightListGeneration(BuildGPULightListPassData data, ComputeCommandBuffer cmd)
{
if (data.runLightList)
{
// clear atomic offset index
cmd.SetComputeBufferParam(data.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, data.globalLightListAtomic);
cmd.DispatchCompute(data.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, 1, 1, 1);
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, data.globalLightListAtomic);
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs.g_vLayeredLightList, data.output.perVoxelLightLists);
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredOffset, data.output.perVoxelOffset);
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, data.globalLightListAtomic);
if (data.runBigTilePrepass)
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs.g_vBigTileLightList, data.output.bigTileLightList);
if (data.clusterNeedsDepth)
{
cmd.SetComputeTextureParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs.g_depth_tex, data.depthBuffer);
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs.g_logBaseBuffer, data.output.perTileLogBaseTweak);
}
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs.g_vBoundsBuffer, data.AABBBoundsBuffer);
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs._LightVolumeData, data.lightVolumeDataBuffer);
cmd.SetComputeBufferParam(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, HDShaderIDs.g_data, data.convexBoundsBuffer);
ConstantBuffer.Push(cmd, data.lightListCB, data.buildPerVoxelLightListShader, HDShaderIDs._ShaderVariablesLightList);
cmd.DispatchCompute(data.buildPerVoxelLightListShader, data.buildPerVoxelLightListKernel, data.numTilesClusterX, data.numTilesClusterY, data.viewCount);
}
}
static void BuildDispatchIndirectArguments(BuildGPULightListPassData data, bool tileFlagsWritten, ComputeCommandBuffer cmd)
{
if (data.enableFeatureVariants)
{
// We need to touch up the tile flags if we need material classification or, if disabled, to patch up for missing flags during the skipped light tile gen
bool needModifyingTileFeatures = !tileFlagsWritten || data.computeMaterialVariants;
if (needModifyingTileFeatures)
{
int buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel;
data.buildMaterialFlagsShader.shaderKeywords = null;
if (tileFlagsWritten && data.computeLightVariants)
{
data.buildMaterialFlagsShader.EnableKeyword("USE_OR");
}
uint baseFeatureFlags = 0;
if (!data.computeLightVariants)
{
baseFeatureFlags |= LightDefinitions.s_LightFeatureMaskFlags;
}
// If we haven't run the light list building, we are missing some basic lighting flags.
if (!tileFlagsWritten)
{
if (data.directionalLightCount > 0)
{
baseFeatureFlags |= (uint)LightFeatureFlags.Directional;
}
if (data.skyEnabled)
{
baseFeatureFlags |= (uint)LightFeatureFlags.Sky;
}
if (!data.computeMaterialVariants)
{
baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags;
}
}
var localLightListCB = data.lightListCB;
localLightListCB.g_BaseFeatureFlags = baseFeatureFlags;
cmd.SetComputeBufferParam(data.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, data.output.tileFeatureFlags);
for (int i = 0; i < data.gBufferCount; ++i)
cmd.SetComputeTextureParam(data.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], data.gBuffer[i]);
RTHandle stencilTexture = data.stencilTexture;
if (stencilTexture?.rt != null && stencilTexture.rt.stencilFormat != GraphicsFormat.None)
{
cmd.SetComputeTextureParam(data.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, data.stencilTexture, 0, RenderTextureSubElement.Stencil);
}
else // We are accessing MSAA resolved version or default black texture and not the depth stencil buffer directly.
{
cmd.SetComputeTextureParam(data.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, data.stencilTexture);
}
ConstantBuffer.Push(cmd, localLightListCB, data.buildMaterialFlagsShader, HDShaderIDs._ShaderVariablesLightList);
cmd.DispatchCompute(data.buildMaterialFlagsShader, buildMaterialFlagsKernel, data.numTilesFPTLX, data.numTilesFPTLY, data.viewCount);
}
// clear dispatch indirect buffer
cmd.SetComputeBufferParam(data.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, data.output.dispatchIndirectBuffer);
cmd.DispatchCompute(data.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDUtils.DivRoundUp(LightDefinitions.s_NumFeatureVariants, k_ThreadGroupOptimalSize), 1, data.viewCount);
// add tiles to indirect buffer
cmd.SetComputeBufferParam(data.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, data.output.dispatchIndirectBuffer);
cmd.SetComputeBufferParam(data.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, data.output.tileList);
cmd.SetComputeBufferParam(data.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, data.output.tileFeatureFlags);
cmd.SetComputeIntParam(data.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, data.numTilesFPTL);
cmd.SetComputeIntParam(data.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, data.numTilesFPTLX);
// Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel
cmd.DispatchCompute(data.buildDispatchIndirectShader, s_BuildIndirectKernel, (data.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, data.viewCount);
}
}
unsafe void PrepareBuildGPULightListPassData(
RenderGraph renderGraph,
IComputeRenderGraphBuilder builder,
HDCamera hdCamera,
TileAndClusterData tileAndClusterData,
ref ShaderVariablesLightList constantBuffer,
int totalLightCount,
TextureHandle depthStencilBuffer,
TextureHandle stencilBufferCopy,
GBufferOutput gBuffer,
BuildGPULightListPassData passData)
{
var camera = hdCamera.camera;
var w = (int)hdCamera.screenSize.x;
var h = (int)hdCamera.screenSize.y;
// Fill the shared constant buffer.
// We don't fill directly the one in the parameter struct because we will need those parameters for volumetric lighting as well.
ref var cb = ref constantBuffer;
var temp = new Matrix4x4();
temp.SetRow(0, new Vector4(0.5f * w, 0.0f, 0.0f, 0.5f * w));
temp.SetRow(1, new Vector4(0.0f, 0.5f * h, 0.0f, 0.5f * h));
temp.SetRow(2, new Vector4(0.0f, 0.0f, 0.5f, 0.5f));
temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
// camera to screen matrix (and it's inverse)
for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex)
{
var proj = hdCamera.xr.enabled ? hdCamera.xr.GetProjMatrix(viewIndex) : camera.projectionMatrix;
// Note: we need to take into account the TAA jitter when indexing the light list
proj = hdCamera.RequiresCameraJitter() ? hdCamera.GetJitteredProjectionMatrix(proj) : proj;
m_LightListProjMatrices[viewIndex] = proj * s_FlipMatrixLHSRHS;
var tempMatrix = temp * m_LightListProjMatrices[viewIndex];
var invTempMatrix = tempMatrix.inverse;
for (int i = 0; i < 16; ++i)
{
cb.g_mScrProjectionArr[viewIndex * 16 + i] = tempMatrix[i];
cb.g_mInvScrProjectionArr[viewIndex * 16 + i] = invTempMatrix[i];
}
}
// camera to screen matrix (and it's inverse)
for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex)
{
temp.SetRow(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
temp.SetRow(1, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
temp.SetRow(2, new Vector4(0.0f, 0.0f, 0.5f, 0.5f));
temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
var tempMatrix = temp * m_LightListProjMatrices[viewIndex];
var invTempMatrix = tempMatrix.inverse;
for (int i = 0; i < 16; ++i)
{
cb.g_mProjectionArr[viewIndex * 16 + i] = tempMatrix[i];
cb.g_mInvProjectionArr[viewIndex * 16 + i] = invTempMatrix[i];
}
}
var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen);
cb.g_iNrVisibLights = totalLightCount;
cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one.
cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y);
cb.g_isOrthographic = camera.orthographic ? 1u : 0u;
cb.g_BaseFeatureFlags = 0; // Filled for each individual pass.
cb.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples;
cb._EnvLightIndexShift = (uint)m_GpuLightsBuilder.lightsCount;
cb._DecalIndexShift = (uint)(m_GpuLightsBuilder.lightsCount + m_lightList.envLights.Count);
// Copy the constant buffer into the parameter struct.
passData.lightListCB = cb;
passData.totalLightCount = totalLightCount;
passData.runLightList = passData.totalLightCount > 0;
passData.clearLightLists = false;
// TODO RENDERGRAPH: This logic is flawed with Render Graph.
// In theory buffers memory might be reused from another usage entirely so keeping track of its "cleared" state does not represent the truth of their content.
// In practice though, when resolution stays the same, buffers will be the same reused from one frame to another
// because for now buffers are pooled based on their passData. When we do proper aliasing though, we might end up with any random chunk of memory.
if (!tileAndClusterData.listsAreInitialized)
{
// On some platforms initial values in buffer might not be zero but random data.
// In the case of buffer "PerVoxelOffset" this can cause GPU to access incorrect memory locations and crash.
// To avoid that we make sure that the buffers are cleared at least once before they start being used.
passData.clearLightLists = true;
tileAndClusterData.listsAreInitialized = true;
}
// Always build the light list in XR mode to avoid issues with multi-pass
if (hdCamera.xr.enabled)
{
passData.runLightList = true;
}
else if (!passData.runLightList && !tileAndClusterData.listsAreClear)
{
passData.clearLightLists = true;
// After that, No need to clear it anymore until we start and stop running light list building.
tileAndClusterData.listsAreClear = true;
}
else if (passData.runLightList)
{
tileAndClusterData.listsAreClear = false;
}
passData.viewCount = hdCamera.viewCount;
passData.enableFeatureVariants = GetFeatureVariantsEnabled(hdCamera.frameSettings) && tileAndClusterData.hasTileBuffers;
passData.computeMaterialVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeMaterialVariants);
passData.computeLightVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeLightVariants);
passData.directionalLightCount = m_GpuLightsBuilder.directionalLightCount;
passData.canClearLightList = m_GpuLightsBuilder != null && m_lightList != null;
passData.skyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera);
bool isProjectionOblique = GeometryUtils.IsProjectionMatrixOblique(m_LightListProjMatrices[0]);
// Clear light lsts
passData.clearLightListCS = runtimeShaders.clearLightListsCS;
passData.clearLightListKernel = passData.clearLightListCS.FindKernel("ClearList");
// Screen space AABB
passData.screenSpaceAABBShader = buildScreenAABBShader;
passData.screenSpaceAABBKernel = 0;
// Big tile prepass
passData.runBigTilePrepass = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass);
passData.bigTilePrepassShader = buildPerBigTileLightListShader;
passData.bigTilePrepassKernel = s_GenListPerBigTileKernel;
passData.numBigTilesX = (w + 63) / 64;
passData.numBigTilesY = (h + 63) / 64;
passData.supportsVolumetric = currentAsset.currentPlatformRenderPipelineSettings.supportVolumetrics;
// Fptl
passData.runFPTL = hdCamera.frameSettings.fptl && tileAndClusterData.hasTileBuffers;
passData.buildPerTileLightListShader = buildPerTileLightListShader;
passData.buildPerTileLightListShader.shaderKeywords = null;
if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass))
{
passData.buildPerTileLightListShader.EnableKeyword("USE_TWO_PASS_TILED_LIGHTING");
}
if (isProjectionOblique)
{
passData.buildPerTileLightListShader.EnableKeyword("USE_OBLIQUE_MODE");
}
if (GetFeatureVariantsEnabled(hdCamera.frameSettings))
{
passData.buildPerTileLightListShader.EnableKeyword("USE_FEATURE_FLAGS");
}
passData.buildPerTileLightListKernel = s_GenListPerTileKernel;
passData.numTilesFPTLX = GetNumTileFtplX(hdCamera);
passData.numTilesFPTLY = GetNumTileFtplY(hdCamera);
passData.numTilesFPTL = passData.numTilesFPTLX * passData.numTilesFPTLY;
// Cluster
bool msaa = hdCamera.msaaEnabled;
var clustPrepassSourceIdx = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass) ? ClusterPrepassSource.BigTile : ClusterPrepassSource.None;
var clustDepthSourceIdx = ClusterDepthSource.NoDepth;
if (tileAndClusterData.clusterNeedsDepth)
clustDepthSourceIdx = msaa ? ClusterDepthSource.MSAA_Depth : ClusterDepthSource.Depth;
passData.buildPerVoxelLightListShader = buildPerVoxelLightListShader;
passData.clearClusterAtomicIndexShader = clearClusterAtomicIndexShader;
passData.buildPerVoxelLightListKernel = isProjectionOblique ? s_ClusterObliqueKernels[(int)clustPrepassSourceIdx, (int)clustDepthSourceIdx] : s_ClusterKernels[(int)clustPrepassSourceIdx, (int)clustDepthSourceIdx];
passData.numTilesClusterX = GetNumTileClusteredX(hdCamera);
passData.numTilesClusterY = GetNumTileClusteredY(hdCamera);
passData.clusterNeedsDepth = tileAndClusterData.clusterNeedsDepth;
// Build dispatch indirect
passData.buildMaterialFlagsShader = buildMaterialFlagsShader;
passData.clearDispatchIndirectShader = clearDispatchIndirectShader;
passData.buildDispatchIndirectShader = buildDispatchIndirectShader;
passData.buildDispatchIndirectShader.shaderKeywords = null;
// Depending on frame setting configurations we might not have written to a depth buffer yet so when executing the pass it might not be valid.
if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.OpaqueObjects))
{
passData.depthBuffer = depthStencilBuffer;
passData.stencilTexture = stencilBufferCopy;
}
else
{
passData.depthBuffer = renderGraph.defaultResources.blackTextureXR;
passData.stencilTexture = renderGraph.defaultResources.blackTextureXR;
}
builder.UseTexture(passData.depthBuffer, AccessFlags.Read);
builder.UseTexture(passData.stencilTexture, AccessFlags.Read);
if (passData.computeMaterialVariants && passData.enableFeatureVariants)
{
// When opaques are disabled, gbuffer count is zero.
// Unfortunately, compute shader will then complains some textures aren't bound, so we need to use black textures instead.
for (int i = 0; i < gBuffer.gBufferCount; ++i)
{
passData.gBuffer[i] = gBuffer.mrt[i];
builder.UseTexture(passData.gBuffer[i], AccessFlags.Read);
}
for (int i = gBuffer.gBufferCount; i < 7; ++i) {
passData.gBuffer[i] = renderGraph.defaultResources.blackTextureXR;
builder.UseTexture(passData.gBuffer[i], AccessFlags.Read);
}
passData.gBufferCount = 7;
}
// Here we use m_MaxViewCount/m_MaxWidthHeight to avoid always allocating buffers of different sizes for each camera.
// This way we'll be reusing them more often.
// Those buffer are filled with the CPU outside of the render graph.
passData.convexBoundsBuffer = renderGraph.ImportBuffer(tileAndClusterData.convexBoundsBuffer);
builder.UseBuffer(passData.convexBoundsBuffer, AccessFlags.Read);
passData.lightVolumeDataBuffer = renderGraph.ImportBuffer(tileAndClusterData.lightVolumeDataBuffer);
builder.UseBuffer(passData.lightVolumeDataBuffer, AccessFlags.Read);
passData.globalLightListAtomic = builder.CreateTransientBuffer(new BufferDesc(1, sizeof(uint)) { name = "LightListAtomic" });
passData.AABBBoundsBuffer = builder.CreateTransientBuffer(new BufferDesc(m_MaxViewCount * 2 * tileAndClusterData.maxLightCount, 4 * sizeof(float)) { name = "AABBBoundBuffer" });
var nrTilesX = (m_MaxCameraWidth + LightDefinitions.s_TileSizeFptl - 1) / LightDefinitions.s_TileSizeFptl;
var nrTilesY = (m_MaxCameraHeight + LightDefinitions.s_TileSizeFptl - 1) / LightDefinitions.s_TileSizeFptl;
var nrTiles = nrTilesX * nrTilesY * m_MaxViewCount;
if (tileAndClusterData.hasTileBuffers)
{
// note that nrTiles include the viewCount in allocation below
// Tile buffers
passData.output.lightList = renderGraph.CreateBuffer(new BufferDesc((int)LightCategory.Count * InternalLightCullingDefs.s_LightDwordPerFptlTile * nrTiles, sizeof(uint)) { name = "LightList" });
builder.UseBuffer(passData.output.lightList, AccessFlags.Write);
passData.output.tileList = renderGraph.CreateBuffer(new BufferDesc(LightDefinitions.s_NumFeatureVariants * nrTiles, sizeof(uint)) { name = "TileList" });
builder.UseBuffer(passData.output.tileList, AccessFlags.Write);
passData.output.tileFeatureFlags = renderGraph.CreateBuffer(new BufferDesc(nrTiles, sizeof(uint)) { name = "TileFeatureFlags" });
builder.UseBuffer(passData.output.tileFeatureFlags, AccessFlags.Write);
// DispatchIndirect: Buffer with arguments has to have three integer numbers at given argsOffset offset: number of work groups in X dimension, number of work groups in Y dimension, number of work groups in Z dimension.
// DrawProceduralIndirect: Buffer with arguments has to have four integer numbers at given argsOffset offset: vertex count per instance, instance count, start vertex location, and start instance location
// Use use max size of 4 unit for allocation
passData.output.dispatchIndirectBuffer = renderGraph.CreateBuffer(new BufferDesc(m_MaxViewCount * LightDefinitions.s_NumFeatureVariants * 4, sizeof(uint), GraphicsBuffer.Target.IndirectArguments) { name = "DispatchIndirectBuffer" });
builder.UseBuffer(passData.output.dispatchIndirectBuffer, AccessFlags.Write);
}
// Big Tile buffer
if (passData.runBigTilePrepass)
{
var nrBigTilesX = (m_MaxCameraWidth + 63) / 64;
var nrBigTilesY = (m_MaxCameraHeight + 63) / 64;
var nrBigTiles = nrBigTilesX * nrBigTilesY * m_MaxViewCount;
passData.output.bigTileLightList = renderGraph.CreateBuffer(new BufferDesc(InternalLightCullingDefs.s_MaxNrBigTileLightsPlusOne * nrBigTiles / 2, sizeof(uint)) { name = "BigTiles" });
builder.UseBuffer(passData.output.bigTileLightList, AccessFlags.Write);
if (passData.supportsVolumetric)
{
passData.output.bigTileVolumetricLightList = renderGraph.CreateBuffer(new BufferDesc(InternalLightCullingDefs.s_MaxNrBigTileLightsPlusOne * nrBigTiles / 2, sizeof(uint)) { name = "BigTiles For Volumetric" });
builder.UseBuffer(passData.output.bigTileVolumetricLightList, AccessFlags.Write);
}
}
// Cluster buffers
var nrClustersX = (m_MaxCameraWidth + LightDefinitions.s_TileSizeClustered - 1) / LightDefinitions.s_TileSizeClustered;
var nrClustersY = (m_MaxCameraHeight + LightDefinitions.s_TileSizeClustered - 1) / LightDefinitions.s_TileSizeClustered;
var nrClusterTiles = nrClustersX * nrClustersY * m_MaxViewCount;
passData.output.perVoxelOffset = renderGraph.CreateBuffer(new BufferDesc((int)LightCategory.Count * (1 << k_Log2NumClusters) * nrClusterTiles, sizeof(uint)) { name = "PerVoxelOffset" });
builder.UseBuffer(passData.output.perVoxelOffset, AccessFlags.Write);
passData.output.perVoxelLightLists = renderGraph.CreateBuffer(new BufferDesc(NumLightIndicesPerClusteredTile() * nrClusterTiles, sizeof(uint)) { name = "PerVoxelLightList" });
builder.UseBuffer(passData.output.perVoxelLightLists, AccessFlags.Write);
if (tileAndClusterData.clusterNeedsDepth)
{
passData.output.perTileLogBaseTweak = renderGraph.CreateBuffer(new BufferDesc(nrClusterTiles, sizeof(float)) { name = "PerTileLogBaseTweak" });
builder.UseBuffer(passData.output.perTileLogBaseTweak, AccessFlags.Write);
}
}
BuildGPULightListOutput BuildGPULightList(
RenderGraph renderGraph,
HDCamera hdCamera,
TileAndClusterData tileAndClusterData,
int totalLightCount,
ref ShaderVariablesLightList constantBuffer,
TextureHandle depthStencilBuffer,
TextureHandle stencilBufferCopy,
GBufferOutput gBuffer)
{
using (var builder = renderGraph.AddComputePass<BuildGPULightListPassData>("Build Light List", out var passData, ProfilingSampler.Get(HDProfileId.BuildLightList)))
{
builder.EnableAsyncCompute(hdCamera.frameSettings.BuildLightListRunsAsync());
builder.AllowGlobalStateModification(true);
PrepareBuildGPULightListPassData(renderGraph, builder, hdCamera, tileAndClusterData, ref constantBuffer, totalLightCount, depthStencilBuffer, stencilBufferCopy, gBuffer, passData);
builder.SetRenderFunc(
(BuildGPULightListPassData data, ComputeGraphContext context) =>
{
bool tileFlagsWritten = false;
ClearLightLists(data, context.cmd);
GenerateLightsScreenSpaceAABBs(data, context.cmd);
BigTilePrepass(data, context.cmd);
BuildPerTileLightList(data, ref tileFlagsWritten, context.cmd);
VoxelLightListGeneration(data, context.cmd);
BuildDispatchIndirectArguments(data, tileFlagsWritten, context.cmd);
});
return passData.output;
}
}
class PushGlobalCameraParamPassData
{
public ShaderVariablesGlobal globalCB;
public ShaderVariablesXR xrCB;
}
void PushGlobalCameraParams(RenderGraph renderGraph, HDCamera hdCamera)
{
using (var builder = renderGraph.AddUnsafePass<PushGlobalCameraParamPassData>("Push Global Camera Parameters", out var passData))
{
builder.AllowGlobalStateModification(true);
passData.globalCB = m_ShaderVariablesGlobalCB;
passData.xrCB = m_ShaderVariablesXRCB;
builder.SetRenderFunc(
(PushGlobalCameraParamPassData data, UnsafeGraphContext ctx) =>
{
ConstantBuffer.PushGlobal(ctx.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal);
ConstantBuffer.PushGlobal(ctx.cmd, data.xrCB, HDShaderIDs._ShaderVariablesXR);
});
}
}
internal ShadowResult RenderShadows(RenderGraph renderGraph, ScriptableRenderContext renderContext, HDCamera hdCamera, CullingResults cullResults, ref ShadowResult result)
{
m_ShadowManager.RenderShadows(m_RenderGraph, renderContext, m_ShaderVariablesGlobalCB, hdCamera, cullResults, ref result);
// Need to restore global camera parameters.
PushGlobalCameraParams(renderGraph, hdCamera);
return result;
}
TextureHandle CreateDiffuseLightingBuffer(RenderGraph renderGraph, MSAASamples msaaSamples)
{
bool msaa = msaaSamples != MSAASamples.None;
return renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
{
format = GraphicsFormat.B10G11R11_UFloatPack32,
enableRandomWrite = !msaa,
bindTextureMS = msaa,
msaaSamples = msaaSamples,
clearBuffer = true,
clearColor = Color.clear,
name = msaa ? "CameraSSSDiffuseLightingMSAA" : "CameraSSSDiffuseLighting"
});
}
class DeferredLightingPassData
{
public int numTilesX;
public int numTilesY;
public int numTiles;
public bool outputSplitLighting;
public bool enableFeatureVariants;
public bool enableShadowMasks;
public int numVariants;
public DebugDisplaySettings debugDisplaySettings;
// Compute Lighting
public ComputeShader deferredComputeShader;
public int viewCount;
public TextureHandle colorBuffer;
public TextureHandle sssDiffuseLightingBuffer;
public TextureHandle depthBuffer;
public TextureHandle depthTexture;
public int gbufferCount;
public int lightLayersTextureIndex;
public int shadowMaskTextureIndex;
public TextureHandle[] gbuffer = new TextureHandle[8];
public BufferHandle lightListBuffer;
public BufferHandle tileFeatureFlagsBuffer;
public BufferHandle tileListBuffer;
public BufferHandle dispatchIndirectBuffer;
public LightingBuffers lightingBuffers;
}
struct LightingOutput
{
public TextureHandle colorBuffer;
}
static void RenderComputeDeferredLighting(DeferredLightingPassData data, RenderTargetIdentifier[] colorBuffers, CommandBuffer cmd)
{
using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderDeferredLightingCompute)))
{
data.deferredComputeShader.shaderKeywords = null;
switch (HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.punctualShadowFilteringQuality)
{
case HDShadowFilteringQuality.Low:
data.deferredComputeShader.EnableKeyword("PUNCTUAL_SHADOW_LOW");
break;
case HDShadowFilteringQuality.Medium:
data.deferredComputeShader.EnableKeyword("PUNCTUAL_SHADOW_MEDIUM");
break;
case HDShadowFilteringQuality.High:
data.deferredComputeShader.EnableKeyword("PUNCTUAL_SHADOW_HIGH");
break;
default:
data.deferredComputeShader.EnableKeyword("PUNCTUAL_SHADOW_MEDIUM");
break;
}
switch (HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.directionalShadowFilteringQuality)
{
case HDShadowFilteringQuality.Low:
data.deferredComputeShader.EnableKeyword("DIRECTIONAL_SHADOW_LOW");
break;
case HDShadowFilteringQuality.Medium:
data.deferredComputeShader.EnableKeyword("DIRECTIONAL_SHADOW_MEDIUM");
break;
case HDShadowFilteringQuality.High:
data.deferredComputeShader.EnableKeyword("DIRECTIONAL_SHADOW_HIGH");
break;
default:
data.deferredComputeShader.EnableKeyword("DIRECTIONAL_SHADOW_MEDIUM");
break;
}
var areaShadowFilteringQuality = (ShaderConfig.s_AreaLights == 0) ? HDAreaShadowFilteringQuality.Medium
: HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.areaShadowFilteringQuality;
switch (areaShadowFilteringQuality)
{
case HDAreaShadowFilteringQuality.Medium:
data.deferredComputeShader.EnableKeyword("AREA_SHADOW_MEDIUM");
break;
case HDAreaShadowFilteringQuality.High:
data.deferredComputeShader.EnableKeyword("AREA_SHADOW_HIGH");
break;
default:
data.deferredComputeShader.EnableKeyword("AREA_SHADOW_MEDIUM");
break;
}
if (data.enableShadowMasks)
{
data.deferredComputeShader.EnableKeyword("SHADOWS_SHADOWMASK");
}
if (data.enableFeatureVariants)
{
for (int variant = 0; variant < data.numVariants; variant++)
{
var kernel = s_shadeOpaqueIndirectFptlKernels[variant];
cmd.SetComputeTextureParam(data.deferredComputeShader, kernel, HDShaderIDs._CameraDepthTexture, data.depthTexture);
// TODO: Is it possible to setup this outside the loop ? Can figure out how, get this: Property (specularLightingUAV) at kernel index (21) is not set
cmd.SetComputeTextureParam(data.deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, colorBuffers[0]);
cmd.SetComputeTextureParam(data.deferredComputeShader, kernel, HDShaderIDs.diffuseLightingUAV, colorBuffers[1]);
cmd.SetComputeBufferParam(data.deferredComputeShader, kernel, HDShaderIDs.g_vLightListTile, data.lightListBuffer);
cmd.SetComputeTextureParam(data.deferredComputeShader, kernel, HDShaderIDs._StencilTexture, data.depthBuffer, 0, RenderTextureSubElement.Stencil);
// always do deferred lighting in blocks of 16x16 (not same as tiled light size)
cmd.SetComputeBufferParam(data.deferredComputeShader, kernel, HDShaderIDs.g_TileFeatureFlags, data.tileFeatureFlagsBuffer);
cmd.SetComputeIntParam(data.deferredComputeShader, HDShaderIDs.g_TileListOffset, variant * data.numTiles * data.viewCount);
cmd.SetComputeBufferParam(data.deferredComputeShader, kernel, HDShaderIDs.g_TileList, data.tileListBuffer);
cmd.DispatchCompute(data.deferredComputeShader, kernel, data.dispatchIndirectBuffer, (uint)variant * 3 * sizeof(uint));
}
}
else
{
var kernel = data.debugDisplaySettings.IsDebugDisplayEnabled() ? s_shadeOpaqueDirectFptlDebugDisplayKernel : s_shadeOpaqueDirectFptlKernel;
cmd.SetComputeTextureParam(data.deferredComputeShader, kernel, HDShaderIDs._CameraDepthTexture, data.depthTexture);
cmd.SetComputeTextureParam(data.deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, colorBuffers[0]);
cmd.SetComputeTextureParam(data.deferredComputeShader, kernel, HDShaderIDs.diffuseLightingUAV, colorBuffers[1]);
cmd.SetComputeBufferParam(data.deferredComputeShader, kernel, HDShaderIDs.g_vLightListTile, data.lightListBuffer);
cmd.SetComputeTextureParam(data.deferredComputeShader, kernel, HDShaderIDs._StencilTexture, data.depthBuffer, 0, RenderTextureSubElement.Stencil);
// 4x 8x8 groups per a 16x16 tile.
cmd.DispatchCompute(data.deferredComputeShader, kernel, data.numTilesX * 2, data.numTilesY * 2, data.viewCount);
}
}
}
LightingOutput RenderDeferredLighting(
RenderGraph renderGraph,
HDCamera hdCamera,
TextureHandle colorBuffer,
TextureHandle depthStencilBuffer,
TextureHandle depthPyramidTexture,
in LightingBuffers lightingBuffers,
in GBufferOutput gbuffer,
in ShadowResult shadowResult,
in BuildGPULightListOutput lightLists)
{
if (hdCamera.frameSettings.litShaderMode != LitShaderMode.Deferred ||
!hdCamera.frameSettings.IsEnabled(FrameSettingsField.OpaqueObjects))
return new LightingOutput();
using (var builder = renderGraph.AddUnsafePass<DeferredLightingPassData>("Deferred Lighting", out var passData))
{
bool debugDisplayOrSceneLightOff = CoreUtils.IsSceneLightingDisabled(hdCamera.camera) || m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled();
int w = hdCamera.actualWidth;
int h = hdCamera.actualHeight;
passData.numTilesX = (w + 15) / 16;
passData.numTilesY = (h + 15) / 16;
passData.numTiles = passData.numTilesX * passData.numTilesY;
passData.outputSplitLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering);
passData.enableFeatureVariants = GetFeatureVariantsEnabled(hdCamera.frameSettings) && !debugDisplayOrSceneLightOff;
passData.enableShadowMasks = m_EnableBakeShadowMask;
passData.numVariants = LightDefinitions.s_NumFeatureVariants;
passData.debugDisplaySettings = m_CurrentDebugDisplaySettings;
// Compute Lighting
passData.deferredComputeShader = deferredComputeShader;
passData.viewCount = hdCamera.viewCount;
passData.colorBuffer = colorBuffer;
builder.UseTexture(passData.colorBuffer, AccessFlags.Write);
if (passData.outputSplitLighting)
{
passData.sssDiffuseLightingBuffer = lightingBuffers.diffuseLightingBuffer;
builder.UseTexture(passData.sssDiffuseLightingBuffer, AccessFlags.Write);
}
else
{
// TODO RENDERGRAPH: Check how to avoid this kind of pattern.
// Unfortunately, the low level needs this texture to always be bound with UAV enabled, so in order to avoid effectively creating the full resolution texture here,
// we need to create a small dummy texture.
passData.sssDiffuseLightingBuffer = builder.CreateTransientTexture(new TextureDesc(1, 1, true, true) { format = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true });
}
passData.depthBuffer = depthStencilBuffer;
builder.UseTexture(passData.depthBuffer, AccessFlags.Read);
passData.depthTexture = depthPyramidTexture;
builder.UseTexture(passData.depthTexture, AccessFlags.Read);
passData.lightingBuffers = ReadLightingBuffers(lightingBuffers, builder);
passData.lightLayersTextureIndex = gbuffer.lightLayersTextureIndex;
passData.shadowMaskTextureIndex = gbuffer.shadowMaskTextureIndex;
passData.gbufferCount = gbuffer.gBufferCount;
for (int i = 0; i < gbuffer.gBufferCount; ++i)
{
passData.gbuffer[i] = gbuffer.mrt[i];
builder.UseTexture(passData.gbuffer[i], AccessFlags.Read);
}
HDShadowManager.ReadShadowResult(shadowResult, builder);
passData.lightListBuffer = lightLists.lightList;
builder.UseBuffer(passData.lightListBuffer, AccessFlags.Read);
passData.tileFeatureFlagsBuffer = lightLists.tileFeatureFlags;
builder.UseBuffer(passData.tileFeatureFlagsBuffer, AccessFlags.Read);
passData.tileListBuffer = lightLists.tileList;
builder.UseBuffer(passData.tileListBuffer, AccessFlags.Read);
passData.dispatchIndirectBuffer = lightLists.dispatchIndirectBuffer;
builder.UseBuffer(passData.dispatchIndirectBuffer, AccessFlags.Read);
builder.AllowGlobalStateModification(true);
var output = new LightingOutput();
output.colorBuffer = passData.colorBuffer;
builder.SetRenderFunc(
(DeferredLightingPassData data, UnsafeGraphContext ctx) =>
{
var natCmd = CommandBufferHelpers.GetNativeCommandBuffer(ctx.cmd);
var colorBuffers = ctx.renderGraphPool.GetTempArray<RenderTargetIdentifier>(2);
colorBuffers[0] = data.colorBuffer;
colorBuffers[1] = data.sssDiffuseLightingBuffer;
// TODO RENDERGRAPH: Remove these SetGlobal and properly send these textures to the deferred passes and bind them directly to compute shaders.
// This can wait that we remove the old code path.
for (int i = 0; i < data.gbufferCount; ++i)
natCmd.SetGlobalTexture(HDShaderIDs._GBufferTexture[i], data.gbuffer[i]);
if (data.lightLayersTextureIndex != -1)
natCmd.SetGlobalTexture(HDShaderIDs._RenderingLayersTexture, data.gbuffer[data.lightLayersTextureIndex]);
else
natCmd.SetGlobalTexture(HDShaderIDs._RenderingLayersTexture, TextureXR.GetWhiteTexture());
if (data.shadowMaskTextureIndex != -1)
natCmd.SetGlobalTexture(HDShaderIDs._ShadowMaskTexture, data.gbuffer[data.shadowMaskTextureIndex]);
else
natCmd.SetGlobalTexture(HDShaderIDs._ShadowMaskTexture, TextureXR.GetWhiteTexture());
BindGlobalLightingBuffers(data.lightingBuffers, natCmd);
RenderComputeDeferredLighting(data, colorBuffers, natCmd);
});
return output;
}
}
class RenderSSRPassData
{
public ComputeShader ssrCS;
public int tracingKernel;
public int reprojectionKernel;
public int accumulateNoWorldSpeedRejectionBothKernel;
public int accumulateNoWorldSpeedRejectionSurfaceKernel;
public int accumulateNoWorldSpeedRejectionHitKernel;