-
Notifications
You must be signed in to change notification settings - Fork 869
Expand file tree
/
Copy pathDeferredLights.cs
More file actions
1348 lines (1146 loc) · 73.3 KB
/
DeferredLights.cs
File metadata and controls
1348 lines (1146 loc) · 73.3 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 System.Runtime.CompilerServices;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Profiling;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine.Rendering.RenderGraphModule;
using static Unity.Mathematics.math;
//#define URP_HAS_BURST
// TODO SimpleLit material, make sure when variant is !defined(_SPECGLOSSMAP) && !defined(_SPECULAR_COLOR), specular is correctly silenced.
// TODO use InitializeSimpleLitSurfaceData() in all shader code
// TODO use InitializeParticleLitSurfaceData() in forward pass for ParticleLitForwardPass.hlsl ? Similar refactoring for ParticleSimpleLitForwardPass.hlsl
// TODO Make sure GPU buffers are uploaded without copying into Unity CommandBuffer memory
// TODO BakedLit.shader has a Universal2D pass, but Unlit.shader doesn't have?
namespace UnityEngine.Rendering.Universal.Internal
{
// Customization per platform.
static class DeferredConfig
{
internal static bool IsOpenGL { get; set; }
// DX10 uses SM 4.0. However URP shaders requires SM 4.5 or will use fallback to SM 2.0 shaders otherwise.
// We will consider deferred renderer is not available when SM 2.0 shaders run.
internal static bool IsDX10 { get; set; }
}
internal enum LightFlag
{
// Keep in sync with kLightFlagSubtractiveMixedLighting.
SubtractiveMixedLighting = 4
}
// Manages deferred lights.
internal class DeferredLights
{
internal static class ShaderConstants
{
public static readonly int _LitStencilRef = Shader.PropertyToID("_LitStencilRef");
public static readonly int _LitStencilReadMask = Shader.PropertyToID("_LitStencilReadMask");
public static readonly int _LitStencilWriteMask = Shader.PropertyToID("_LitStencilWriteMask");
public static readonly int _SimpleLitStencilRef = Shader.PropertyToID("_SimpleLitStencilRef");
public static readonly int _SimpleLitStencilReadMask = Shader.PropertyToID("_SimpleLitStencilReadMask");
public static readonly int _SimpleLitStencilWriteMask = Shader.PropertyToID("_SimpleLitStencilWriteMask");
public static readonly int _StencilRef = Shader.PropertyToID("_StencilRef");
public static readonly int _StencilReadMask = Shader.PropertyToID("_StencilReadMask");
public static readonly int _StencilWriteMask = Shader.PropertyToID("_StencilWriteMask");
public static readonly int _LitPunctualStencilRef = Shader.PropertyToID("_LitPunctualStencilRef");
public static readonly int _LitPunctualStencilReadMask = Shader.PropertyToID("_LitPunctualStencilReadMask");
public static readonly int _LitPunctualStencilWriteMask = Shader.PropertyToID("_LitPunctualStencilWriteMask");
public static readonly int _SimpleLitPunctualStencilRef = Shader.PropertyToID("_SimpleLitPunctualStencilRef");
public static readonly int _SimpleLitPunctualStencilReadMask = Shader.PropertyToID("_SimpleLitPunctualStencilReadMask");
public static readonly int _SimpleLitPunctualStencilWriteMask = Shader.PropertyToID("_SimpleLitPunctualStencilWriteMask");
public static readonly int _LitDirStencilRef = Shader.PropertyToID("_LitDirStencilRef");
public static readonly int _LitDirStencilReadMask = Shader.PropertyToID("_LitDirStencilReadMask");
public static readonly int _LitDirStencilWriteMask = Shader.PropertyToID("_LitDirStencilWriteMask");
public static readonly int _SimpleLitDirStencilRef = Shader.PropertyToID("_SimpleLitDirStencilRef");
public static readonly int _SimpleLitDirStencilReadMask = Shader.PropertyToID("_SimpleLitDirStencilReadMask");
public static readonly int _SimpleLitDirStencilWriteMask = Shader.PropertyToID("_SimpleLitDirStencilWriteMask");
public static readonly int _ClearStencilRef = Shader.PropertyToID("_ClearStencilRef");
public static readonly int _ClearStencilReadMask = Shader.PropertyToID("_ClearStencilReadMask");
public static readonly int _ClearStencilWriteMask = Shader.PropertyToID("_ClearStencilWriteMask");
public static readonly int _ScreenToWorld = Shader.PropertyToID("_ScreenToWorld");
public static int _MainLightPosition = Shader.PropertyToID("_MainLightPosition"); // ForwardLights.LightConstantBuffer also refers to the same ShaderPropertyID - TODO: move this definition to a common location shared by other UniversalRP classes
public static int _MainLightColor = Shader.PropertyToID("_MainLightColor"); // ForwardLights.LightConstantBuffer also refers to the same ShaderPropertyID - TODO: move this definition to a common location shared by other UniversalRP classes
public static int _MainLightLayerMask = Shader.PropertyToID("_MainLightLayerMask"); // ForwardLights.LightConstantBuffer also refers to the same ShaderPropertyID - TODO: move this definition to a common location shared by other UniversalRP classes
public static int _SpotLightScale = Shader.PropertyToID("_SpotLightScale");
public static int _SpotLightBias = Shader.PropertyToID("_SpotLightBias");
public static int _SpotLightGuard = Shader.PropertyToID("_SpotLightGuard");
public static int _LightPosWS = Shader.PropertyToID("_LightPosWS");
public static int _LightColor = Shader.PropertyToID("_LightColor");
public static int _LightAttenuation = Shader.PropertyToID("_LightAttenuation");
public static int _LightOcclusionProbInfo = Shader.PropertyToID("_LightOcclusionProbInfo");
public static int _LightDirection = Shader.PropertyToID("_LightDirection");
public static int _LightFlags = Shader.PropertyToID("_LightFlags");
public static int _ShadowLightIndex = Shader.PropertyToID("_ShadowLightIndex");
public static int _LightLayerMask = Shader.PropertyToID("_LightLayerMask");
public static int _CookieLightIndex = Shader.PropertyToID("_CookieLightIndex");
}
internal static readonly string[] k_GBufferNames = new string[]
{
"_GBuffer0",
"_GBuffer1",
"_GBuffer2",
"_GBuffer3",
"_GBuffer4",
"_GBuffer5",
"_GBuffer6"
};
internal static readonly int[] k_GBufferShaderPropertyIDs = new int[]
{
Shader.PropertyToID(k_GBufferNames[0]),
Shader.PropertyToID(k_GBufferNames[1]),
Shader.PropertyToID(k_GBufferNames[2]),
Shader.PropertyToID(k_GBufferNames[3]),
Shader.PropertyToID(k_GBufferNames[4]),
Shader.PropertyToID(k_GBufferNames[5]),
Shader.PropertyToID(k_GBufferNames[6]),
};
static readonly string[] k_StencilDeferredPassNames = new string[]
{
"Stencil Volume",
"Deferred Punctual Light (Lit)",
"Deferred Punctual Light (SimpleLit)",
"Deferred Directional Light (Lit)",
"Deferred Directional Light (SimpleLit)",
"ClearStencilPartial",
"Fog",
"SSAOOnly"
};
internal enum StencilDeferredPasses
{
StencilVolume,
PunctualLit,
PunctualSimpleLit,
DirectionalLit,
DirectionalSimpleLit,
ClearStencilPartial,
Fog,
SSAOOnly
};
static readonly ushort k_InvalidLightOffset = 0xFFFF;
static readonly string k_SetupLights = "SetupLights";
static readonly string k_DeferredPass = "Deferred Pass";
static readonly string k_DeferredStencilPass = "Deferred Shading (Stencil)";
static readonly string k_DeferredFogPass = "Deferred Fog";
static readonly string k_ClearStencilPartial = "Clear Stencil Partial";
static readonly string k_SetupLightConstants = "Setup Light Constants";
static readonly float kStencilShapeGuard = 1.06067f; // stencil geometric shapes must be inflated to fit the analytic shapes.
private static readonly ProfilingSampler m_ProfilingSetupLights = new ProfilingSampler(k_SetupLights);
private static readonly ProfilingSampler m_ProfilingDeferredPass = new ProfilingSampler(k_DeferredPass);
private static readonly ProfilingSampler m_ProfilingSetupLightConstants = new ProfilingSampler(k_SetupLightConstants);
// Mandatory g-buffers
internal int GBufferAlbedoIndex { get { return 0; } }
internal int GBufferSpecularMetallicIndex { get { return 1; } }
internal int GBufferNormalSmoothnessIndex { get { return 2; } }
// User-defined g-buffers should go here, after the mandatory and before the lighting buffer & optional g-buffers
// Lighting g-buffer (should be the last mandatory g-buffer because it is not passed along as an attachment, so subsequent attachment indices shift)
internal int GBufferLightingIndex { get { return UniversalRenderer.k_GbufferCountMandatory - 1; } }
// Optional g-buffers
internal int GbufferDepthIndex { get { return UseFramebufferFetch ? GBufferLightingIndex + 1 : -1; } }
internal int GBufferRenderingLayers { get { return UseRenderingLayers ? GBufferLightingIndex + (UseFramebufferFetch ? 1 : 0) + 1 : -1; } }
// Shadow Mask can change at runtime. Because of this it needs to come after the non-changing buffers.
internal int GBufferShadowMask { get { return UseShadowMask ? GBufferLightingIndex + (UseFramebufferFetch ? 1 : 0) + (UseRenderingLayers ? 1 : 0) + 1 : -1; } }
// Color buffer count (not including dephStencil).
internal int GBufferSliceCount { get { return UniversalRenderer.k_GbufferCountMandatory + (UseFramebufferFetch ? 1 : 0) + (UseShadowMask ? 1 : 0) + (UseRenderingLayers ? 1 : 0); } }
internal int GBufferInputAttachmentCount { get { return UniversalRenderer.k_GbufferCountMandatory + (UseShadowMask ? 1 : 0); } }
internal GraphicsFormat GetGBufferFormat(int index)
{
if (index == GBufferAlbedoIndex) // sRGB albedo, materialFlags
return QualitySettings.activeColorSpace == ColorSpace.Linear ? GraphicsFormat.R8G8B8A8_SRGB : GraphicsFormat.R8G8B8A8_UNorm;
else if (index == GBufferSpecularMetallicIndex) // sRGB specular, [unused]
return GraphicsFormat.R8G8B8A8_UNorm;
else if (index == GBufferNormalSmoothnessIndex)
return AccurateGbufferNormals ? GraphicsFormat.R8G8B8A8_UNorm : DepthNormalOnlyPass.GetGraphicsFormat(); // normal normal normal packedSmoothness
else if (index == GBufferLightingIndex) // Emissive+baked: Most likely B10G11R11_UFloatPack32 or R16G16B16A16_SFloat
return GraphicsFormat.None;
else if (index == GbufferDepthIndex) // Render-pass on mobiles: reading back real depth-buffer is either inefficient (Arm Vulkan) or impossible (Metal).
return GraphicsFormat.R32_SFloat;
else if (index == GBufferShadowMask) // Optional: shadow mask is outputted in mixed lighting subtractive mode for non-static meshes only
return GraphicsFormat.B8G8R8A8_UNorm;
else if (index == GBufferRenderingLayers) // Optional: rendering layers is outputted when light layers are enabled (subset of rendering layers)
return RenderingLayerUtils.GetFormat(RenderingLayerMaskSize);
else
return GraphicsFormat.None;
}
// This may return different values depending on what lights are rendered for a given frame.
internal bool UseShadowMask { get { return this.MixedLightingSetup != MixedLightingSetup.None; } }
//
internal bool UseRenderingLayers { get { return UseLightLayers || UseDecalLayers; } }
//
internal RenderingLayerUtils.MaskSize RenderingLayerMaskSize { get; set; }
//
internal bool UseDecalLayers { get; set; }
//
internal bool UseLightLayers { get { return UniversalRenderPipeline.asset.useRenderingLayers; } }
//
internal bool UseFramebufferFetch { get; set; }
//
internal bool HasDepthPrepass { get; set; }
//
internal bool HasNormalPrepass { get; set; }
internal bool HasRenderingLayerPrepass { get; set; }
// This is an overlay camera being rendered.
internal bool IsOverlay { get; set; }
internal bool AccurateGbufferNormals { get; set; }
// We browse all visible lights and found the mixed lighting setup every frame.
internal MixedLightingSetup MixedLightingSetup { get; set; }
//
internal bool UseJobSystem { get; set; }
//
internal int RenderWidth { get; set; }
//
internal int RenderHeight { get; set; }
// Output lighting result.
internal RTHandle[] GbufferAttachments { get; set; }
private RTHandle[] GbufferRTHandles;
internal TextureHandle[] GbufferTextureHandles { get; set; }
internal RTHandle[] DeferredInputAttachments { get; set; }
internal bool[] DeferredInputIsTransient { get; set; }
// Input depth texture, also bound as read-only RT
internal RTHandle DepthAttachment { get; set; }
//
internal RTHandle DepthCopyTexture { get; set; }
internal GraphicsFormat[] GbufferFormats { get; set; }
internal RTHandle DepthAttachmentHandle { get; set; }
// Visible lights indices rendered using stencil volumes.
NativeArray<ushort> m_stencilVisLights;
// Offset of each type of lights in m_stencilVisLights.
NativeArray<ushort> m_stencilVisLightOffsets;
// Needed to access light shadow index (can be null if the pass is not queued).
AdditionalLightsShadowCasterPass m_AdditionalLightsShadowCasterPass;
// For rendering stencil point lights.
Mesh m_SphereMesh;
// For rendering stencil spot lights.
Mesh m_HemisphereMesh;
// For rendering directional lights.
Mesh m_FullscreenMesh;
// Hold all shaders for stencil-volume deferred shading.
Material m_StencilDeferredMaterial;
// Pass indices.
int[] m_StencilDeferredPasses;
// Avoid memory allocations.
Matrix4x4[] m_ScreenToWorld = new Matrix4x4[2];
ProfilingSampler m_ProfilingSamplerDeferredStencilPass = new ProfilingSampler(k_DeferredStencilPass);
ProfilingSampler m_ProfilingSamplerDeferredFogPass = new ProfilingSampler(k_DeferredFogPass);
ProfilingSampler m_ProfilingSamplerClearStencilPartialPass = new ProfilingSampler(k_ClearStencilPartial);
private LightCookieManager m_LightCookieManager;
internal struct InitParams
{
public Material stencilDeferredMaterial;
public LightCookieManager lightCookieManager;
}
internal DeferredLights(InitParams initParams, bool useNativeRenderPass = false)
{
// Cache result for GL platform here. SystemInfo properties are in C++ land so repeated access will be unecessary penalized.
// They can also only be called from main thread!
DeferredConfig.IsOpenGL = SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3;
// Cachre result for DX10 platform too. Same reasons as above.
DeferredConfig.IsDX10 = SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11 && SystemInfo.graphicsShaderLevel <= 40;
m_StencilDeferredMaterial = initParams.stencilDeferredMaterial;
m_StencilDeferredPasses = new int[k_StencilDeferredPassNames.Length];
InitStencilDeferredMaterial();
this.AccurateGbufferNormals = true;
this.UseJobSystem = true;
this.UseFramebufferFetch = useNativeRenderPass;
m_LightCookieManager = initParams.lightCookieManager;
}
static ProfilingSampler s_SetupDeferredLights = new ProfilingSampler("Setup Deferred lights");
private class SetupLightPassData
{
internal UniversalCameraData cameraData;
internal UniversalLightData lightData;
internal DeferredLights deferredLights;
// The size of the camera target changes during the frame so we must make a copy of it here to preserve its record-time value.
internal Vector2Int cameraTargetSizeCopy;
};
/// <summary>
/// Sets up the ForwardLight data for RenderGraph execution
/// </summary>
internal void SetupRenderGraphLights(RenderGraph renderGraph, UniversalCameraData cameraData, UniversalLightData lightData)
{
using (var builder = renderGraph.AddUnsafePass<SetupLightPassData>(s_SetupDeferredLights.name, out var passData,
s_SetupDeferredLights))
{
passData.cameraData = cameraData;
passData.cameraTargetSizeCopy = new Vector2Int(cameraData.cameraTargetDescriptor.width, cameraData.cameraTargetDescriptor.height);
passData.lightData = lightData;
passData.deferredLights = this;
builder.AllowPassCulling(false);
builder.SetRenderFunc((SetupLightPassData data, UnsafeGraphContext rgContext) =>
{
data.deferredLights.SetupLights(CommandBufferHelpers.GetNativeCommandBuffer(rgContext.cmd), data.cameraData, data.cameraTargetSizeCopy, data.lightData, true);
});
}
}
internal void SetupLights(CommandBuffer cmd, UniversalCameraData cameraData, Vector2Int cameraTargetSizeCopy, UniversalLightData lightData, bool isRenderGraph = false)
{
Profiler.BeginSample(k_SetupLights);
Camera camera = cameraData.camera;
// Support for dynamic resolution.
this.RenderWidth = camera.allowDynamicResolution ? Mathf.CeilToInt(ScalableBufferManager.widthScaleFactor * cameraTargetSizeCopy.x) : cameraTargetSizeCopy.x;
this.RenderHeight = camera.allowDynamicResolution ? Mathf.CeilToInt(ScalableBufferManager.heightScaleFactor * cameraTargetSizeCopy.y) : cameraTargetSizeCopy.y;
// inspect lights in lightData.visibleLights and convert them to entries in m_stencilVisLights
PrecomputeLights(
out m_stencilVisLights,
out m_stencilVisLightOffsets,
ref lightData.visibleLights,
lightData.additionalLightsCount != 0 || lightData.mainLightIndex >= 0
);
{
using (new ProfilingScope(cmd, m_ProfilingSetupLightConstants))
{
// Shared uniform constants for all lights.
SetupShaderLightConstants(cmd, lightData);
#if UNITY_EDITOR
// This flag is used to strip mixed lighting shader variants when a player is built.
// All shader variants are available in the editor.
bool supportsMixedLighting = true;
#else
bool supportsMixedLighting = lightData.supportsMixedLighting;
#endif
// Setup global keywords.
cmd.SetKeyword(ShaderGlobalKeywords._GBUFFER_NORMALS_OCT, this.AccurateGbufferNormals);
bool isShadowMask = supportsMixedLighting && this.MixedLightingSetup == MixedLightingSetup.ShadowMask;
bool isShadowMaskAlways = isShadowMask && QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask;
bool isSubtractive = supportsMixedLighting && this.MixedLightingSetup == MixedLightingSetup.Subtractive;
cmd.SetKeyword(ShaderGlobalKeywords.LightmapShadowMixing, isSubtractive || isShadowMaskAlways);
cmd.SetKeyword(ShaderGlobalKeywords.ShadowsShadowMask, isShadowMask);
cmd.SetKeyword(ShaderGlobalKeywords.MixedLightingSubtractive, isSubtractive); // Backward compatibility
// This should be moved to a more global scope when framebuffer fetch is introduced to more passes
cmd.SetKeyword(ShaderGlobalKeywords.RenderPassEnabled, this.UseFramebufferFetch && (cameraData.cameraType == CameraType.Game || camera.cameraType == CameraType.SceneView || isRenderGraph));
cmd.SetKeyword(ShaderGlobalKeywords.LightLayers, UseLightLayers && !CoreUtils.IsSceneLightingDisabled(camera));
RenderingLayerUtils.SetupProperties(cmd, RenderingLayerMaskSize);
}
}
Profiler.EndSample();
}
internal void ResolveMixedLightingMode(UniversalLightData lightData)
{
// Find the mixed lighting mode. This is the same logic as ForwardLights.
this.MixedLightingSetup = MixedLightingSetup.None;
#if !UNITY_EDITOR
// This flag is used to strip mixed lighting shader variants when a player is built.
// All shader variants are available in the editor.
if (lightData.supportsMixedLighting)
#endif
{
NativeArray<VisibleLight> visibleLights = lightData.visibleLights;
for (int lightIndex = 0; lightIndex < lightData.visibleLights.Length && this.MixedLightingSetup == MixedLightingSetup.None; ++lightIndex)
{
Light light = visibleLights.UnsafeElementAtMutable(lightIndex).light;
if (light != null
&& light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed
&& light.shadows != LightShadows.None)
{
switch (light.bakingOutput.mixedLightingMode)
{
case MixedLightingMode.Subtractive:
this.MixedLightingSetup = MixedLightingSetup.Subtractive;
break;
case MixedLightingMode.Shadowmask:
this.MixedLightingSetup = MixedLightingSetup.ShadowMask;
break;
}
}
}
}
// Once the mixed lighting mode has been discovered, we know how many MRTs we need for the gbuffer.
// Subtractive mixed lighting requires shadowMask output, which is actually used to store unity_ProbesOcclusion values.
CreateGbufferResources();
}
// In cases when custom pass is injected between GBuffer and Deferred passes we need to fallback
// To non-renderpass path in the middle of setup, which means recreating the gbuffer attachments as well due to GBuffer4 used for RenderPass
internal void DisableFramebufferFetchInput()
{
this.UseFramebufferFetch = false;
CreateGbufferResources();
}
internal void ReleaseGbufferResources()
{
if (this.GbufferRTHandles != null)
{
// Release the old handles before creating the new one
for (int i = 0; i < this.GbufferRTHandles.Length; ++i)
{
if (i == GBufferLightingIndex) // Not on GBuffer to release
continue;
this.GbufferRTHandles[i].Release();
this.GbufferAttachments[i].Release();
}
}
}
internal void ReAllocateGBufferIfNeeded(RenderTextureDescriptor gbufferSlice, int gbufferIndex)
{
if (this.GbufferRTHandles != null)
{
// In case DeferredLight does not own the RTHandle, we can skip realloc.
if (this.GbufferRTHandles[gbufferIndex].GetInstanceID() != this.GbufferAttachments[gbufferIndex].GetInstanceID())
return;
gbufferSlice.depthBufferBits = 0; // make sure no depth surface is actually created
gbufferSlice.stencilFormat = GraphicsFormat.None;
gbufferSlice.graphicsFormat = GetGBufferFormat(gbufferIndex);
RenderingUtils.ReAllocateHandleIfNeeded(ref GbufferRTHandles[gbufferIndex], gbufferSlice, FilterMode.Point, TextureWrapMode.Clamp, name: k_GBufferNames[gbufferIndex]);
GbufferAttachments[gbufferIndex] = GbufferRTHandles[gbufferIndex];
}
}
internal void CreateGbufferResources()
{
int gbufferSliceCount = this.GBufferSliceCount;
if (this.GbufferRTHandles == null || this.GbufferRTHandles.Length != gbufferSliceCount)
{
ReleaseGbufferResources();
this.GbufferAttachments = new RTHandle[gbufferSliceCount];
this.GbufferRTHandles = new RTHandle[gbufferSliceCount];
this.GbufferFormats = new GraphicsFormat[gbufferSliceCount];
this.GbufferTextureHandles = new TextureHandle[gbufferSliceCount];
for (int i = 0; i < gbufferSliceCount; ++i)
{
this.GbufferRTHandles[i] = RTHandles.Alloc(k_GBufferNames[i], name: k_GBufferNames[i]);
this.GbufferAttachments[i] = this.GbufferRTHandles[i];
this.GbufferFormats[i] = this.GetGBufferFormat(i);
}
}
}
internal void UpdateDeferredInputAttachments()
{
this.DeferredInputAttachments[0] = this.GbufferAttachments[0];
this.DeferredInputAttachments[1] = this.GbufferAttachments[1];
this.DeferredInputAttachments[2] = this.GbufferAttachments[2];
// NOTE: Lighting buffer (GbufferAttachments[3]) is skipped. Subsequent attachment indices will be off by 1 compared to their g-buffer indices
// TODO: Can this be this.GbufferAttachments[GbufferDepthIndex] instead of this.GbufferAttachments[4] ?
this.DeferredInputAttachments[UniversalRenderer.k_GbufferCountMandatory - 1] = this.GbufferAttachments[4];
if (UseShadowMask && UseRenderingLayers)
{
this.DeferredInputAttachments[UniversalRenderer.k_GbufferCountMandatory] = this.GbufferAttachments[GBufferShadowMask];
this.DeferredInputAttachments[UniversalRenderer.k_GbufferCountMandatory + 1] = this.GbufferAttachments[GBufferRenderingLayers];
}
else if (UseShadowMask)
{
this.DeferredInputAttachments[UniversalRenderer.k_GbufferCountMandatory] = this.GbufferAttachments[GBufferShadowMask];
}
else if (UseRenderingLayers)
{
this.DeferredInputAttachments[UniversalRenderer.k_GbufferCountMandatory] = this.GbufferAttachments[GBufferRenderingLayers];
}
}
internal bool IsRuntimeSupportedThisFrame()
{
// GBuffer slice count can change depending actual geometry/light being rendered.
// For instance, we only bind shadowMask RT if the scene supports mix lighting and at least one visible light has subtractive mixed ligting mode.
return this.GBufferSliceCount <= SystemInfo.supportedRenderTargetCount && !DeferredConfig.IsOpenGL && !DeferredConfig.IsDX10;
}
public void Setup(
AdditionalLightsShadowCasterPass additionalLightsShadowCasterPass,
bool hasDepthPrepass,
bool hasNormalPrepass,
bool hasRenderingLayerPrepass,
RTHandle depthCopyTexture,
RTHandle depthAttachment,
RTHandle colorAttachment)
{
m_AdditionalLightsShadowCasterPass = additionalLightsShadowCasterPass;
this.HasDepthPrepass = hasDepthPrepass;
this.HasNormalPrepass = hasNormalPrepass;
this.HasRenderingLayerPrepass = hasRenderingLayerPrepass;
this.DepthCopyTexture = depthCopyTexture;
this.GbufferAttachments[this.GBufferLightingIndex] = colorAttachment;
this.DepthAttachment = depthAttachment;
var inputCount = UniversalRenderer.k_GbufferCountMandatory + (UseShadowMask ? 1 : 0) + (UseRenderingLayers ? 1 : 0);
if (this.DeferredInputAttachments == null && this.UseFramebufferFetch && this.GbufferAttachments.Length >= 3 + UniversalRenderer.k_GbufferCountUserDefined ||
(this.DeferredInputAttachments != null && inputCount != this.DeferredInputAttachments.Length))
{
this.DeferredInputAttachments = new RTHandle[inputCount];
this.DeferredInputIsTransient = new bool[inputCount];
int i, j = 0;
for (i = 0; i < inputCount; i++, j++)
{
// Do not include the lighting g-buffer as an attachment. Note that this means that all of the
// optional attachment indices are shifted by 1 compared to their g-buffer indices
if (j == GBufferLightingIndex)
j++;
DeferredInputAttachments[i] = GbufferAttachments[j];
DeferredInputIsTransient[i] = j != GbufferDepthIndex;
}
}
this.DepthAttachmentHandle = this.DepthAttachment;
}
// Only used by RenderGraph now as the other Setup call requires providing target handles which isn't working on RG
internal void Setup(AdditionalLightsShadowCasterPass additionalLightsShadowCasterPass)
{
m_AdditionalLightsShadowCasterPass = additionalLightsShadowCasterPass;
}
public void OnCameraCleanup(CommandBuffer cmd)
{
// Disable any global keywords setup in SetupLights().
cmd.SetKeyword(ShaderGlobalKeywords._GBUFFER_NORMALS_OCT, false);
if (m_stencilVisLights.IsCreated)
m_stencilVisLights.Dispose();
if (m_stencilVisLightOffsets.IsCreated)
m_stencilVisLightOffsets.Dispose();
}
internal static StencilState OverwriteStencil(StencilState s, int stencilWriteMask)
{
if (!s.enabled)
{
return new StencilState(
true,
0, (byte)stencilWriteMask,
CompareFunction.Always, StencilOp.Replace, StencilOp.Keep, StencilOp.Keep,
CompareFunction.Always, StencilOp.Replace, StencilOp.Keep, StencilOp.Keep
);
}
CompareFunction funcFront = s.compareFunctionFront != CompareFunction.Disabled ? s.compareFunctionFront : CompareFunction.Always;
CompareFunction funcBack = s.compareFunctionBack != CompareFunction.Disabled ? s.compareFunctionBack : CompareFunction.Always;
StencilOp passFront = s.passOperationFront;
StencilOp failFront = s.failOperationFront;
StencilOp zfailFront = s.zFailOperationFront;
StencilOp passBack = s.passOperationBack;
StencilOp failBack = s.failOperationBack;
StencilOp zfailBack = s.zFailOperationBack;
return new StencilState(
true,
(byte)(s.readMask & 0x0F), (byte)(s.writeMask | stencilWriteMask),
funcFront, passFront, failFront, zfailFront,
funcBack, passBack, failBack, zfailBack
);
}
internal static RenderStateBlock OverwriteStencil(RenderStateBlock block, int stencilWriteMask, int stencilRef)
{
if (!block.stencilState.enabled)
{
block.stencilState = new StencilState(
true,
0, (byte)stencilWriteMask,
CompareFunction.Always, StencilOp.Replace, StencilOp.Keep, StencilOp.Keep,
CompareFunction.Always, StencilOp.Replace, StencilOp.Keep, StencilOp.Keep
);
}
else
{
StencilState s = block.stencilState;
CompareFunction funcFront = s.compareFunctionFront != CompareFunction.Disabled ? s.compareFunctionFront : CompareFunction.Always;
CompareFunction funcBack = s.compareFunctionBack != CompareFunction.Disabled ? s.compareFunctionBack : CompareFunction.Always;
StencilOp passFront = s.passOperationFront;
StencilOp failFront = s.failOperationFront;
StencilOp zfailFront = s.zFailOperationFront;
StencilOp passBack = s.passOperationBack;
StencilOp failBack = s.failOperationBack;
StencilOp zfailBack = s.zFailOperationBack;
block.stencilState = new StencilState(
true,
(byte)(s.readMask & 0x0F), (byte)(s.writeMask | stencilWriteMask),
funcFront, passFront, failFront, zfailFront,
funcBack, passBack, failBack, zfailBack
);
}
block.mask |= RenderStateMask.Stencil;
block.stencilReference = (block.stencilReference & (int)StencilUsage.UserMask) | stencilRef;
return block;
}
internal void ClearStencilPartial(RasterCommandBuffer cmd)
{
if (m_FullscreenMesh == null)
m_FullscreenMesh = CreateFullscreenMesh();
using (new ProfilingScope(cmd, m_ProfilingSamplerClearStencilPartialPass))
{
cmd.DrawMesh(m_FullscreenMesh, Matrix4x4.identity, m_StencilDeferredMaterial, 0, m_StencilDeferredPasses[(int)StencilDeferredPasses.ClearStencilPartial]);
}
}
internal void ExecuteDeferredPass(RasterCommandBuffer cmd, UniversalCameraData cameraData, UniversalLightData lightData, UniversalShadowData shadowData)
{
// Workaround for bug.
// When changing the URP asset settings (ex: shadow cascade resolution), all ScriptableRenderers are recreated but
// materials passed in have not finished initializing at that point if they have fallback shader defined. In particular deferred shaders only have 1 pass available,
// which prevents from resolving correct pass indices.
if (m_StencilDeferredPasses[0] < 0)
InitStencilDeferredMaterial();
if (!UseFramebufferFetch)
{
for (int i = 0; i < GbufferTextureHandles.Length; i++)
{
if (i != GBufferLightingIndex)
m_StencilDeferredMaterial.SetTexture(k_GBufferShaderPropertyIDs[i], GbufferTextureHandles[i]);
}
}
using (new ProfilingScope(cmd, m_ProfilingDeferredPass))
{
// This does 2 things:
// - baked geometry are skipped (do not receive dynamic lighting)
// - non-baked geometry (== non-static geometry) use shadowMask/occlusionProbes to emulate baked shadows influences.
cmd.SetKeyword(ShaderGlobalKeywords._DEFERRED_MIXED_LIGHTING, this.UseShadowMask);
// This must be set for each eye in XR mode multipass.
SetupMatrixConstants(cmd, cameraData);
// First directional light will apply SSAO if possible, unless there is none.
if (!HasStencilLightsOfType(LightType.Directional))
RenderSSAOBeforeShading(cmd);
RenderStencilLights(cmd, lightData, shadowData, cameraData.renderer.stripShadowsOffVariants);
cmd.SetKeyword(ShaderGlobalKeywords._DEFERRED_MIXED_LIGHTING, false);
// Legacy fog (Windows -> Rendering -> Lighting Settings -> Fog)
RenderFog(cmd, cameraData.camera.orthographic);
}
// Restore shader keywords
cmd.SetKeyword(ShaderGlobalKeywords.AdditionalLightShadows, shadowData.isKeywordAdditionalLightShadowsEnabled);
ShadowUtils.SetSoftShadowQualityShaderKeywords(cmd, shadowData);
cmd.SetKeyword(ShaderGlobalKeywords.LightCookies, m_LightCookieManager != null && m_LightCookieManager.IsKeywordLightCookieEnabled);
}
// adapted from ForwardLights.SetupShaderLightConstants
void SetupShaderLightConstants(CommandBuffer cmd, UniversalLightData lightData)
{
// Main light has an optimized shader path for main light. This will benefit games that only care about a single light.
// Universal Forward pipeline only supports a single shadow light, if available it will be the main light.
SetupMainLightConstants(cmd, lightData);
}
// adapted from ForwardLights.SetupShaderLightConstants
void SetupMainLightConstants(CommandBuffer cmd, UniversalLightData lightData)
{
if (lightData.mainLightIndex < 0)
return;
Vector4 lightPos, lightColor, lightAttenuation, lightSpotDir, lightOcclusionChannel;
UniversalRenderPipeline.InitializeLightConstants_Common(lightData.visibleLights, lightData.mainLightIndex, out lightPos, out lightColor, out lightAttenuation, out lightSpotDir, out lightOcclusionChannel);
if (lightData.supportsLightLayers)
{
Light light = lightData.visibleLights[lightData.mainLightIndex].light;
SetRenderingLayersMask(CommandBufferHelpers.GetRasterCommandBuffer(cmd), light, ShaderConstants._MainLightLayerMask);
}
cmd.SetGlobalVector(ShaderConstants._MainLightPosition, lightPos);
cmd.SetGlobalVector(ShaderConstants._MainLightColor, lightColor);
}
void SetupMatrixConstants(RasterCommandBuffer cmd, UniversalCameraData cameraData)
{
#if ENABLE_VR && ENABLE_XR_MODULE
int eyeCount = cameraData.xr.enabled && cameraData.xr.singlePassEnabled ? 2 : 1;
#else
int eyeCount = 1;
#endif
Matrix4x4[] screenToWorld = m_ScreenToWorld; // deferred shaders expects 2 elements
for (int eyeIndex = 0; eyeIndex < eyeCount; eyeIndex++)
{
Matrix4x4 proj = cameraData.GetProjectionMatrix(eyeIndex);
Matrix4x4 view = cameraData.GetViewMatrix(eyeIndex);
Matrix4x4 gpuProj = GL.GetGPUProjectionMatrix(proj, false);
// xy coordinates in range [-1; 1] go to pixel coordinates.
Matrix4x4 toScreen = new Matrix4x4(
new Vector4(0.5f * this.RenderWidth, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.5f * this.RenderHeight, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, 1.0f, 0.0f),
new Vector4(0.5f * this.RenderWidth, 0.5f * this.RenderHeight, 0.0f, 1.0f)
);
Matrix4x4 zScaleBias = Matrix4x4.identity;
if (DeferredConfig.IsOpenGL)
{
// We need to manunally adjust z in NDC space from [-1; 1] to [0; 1] (storage in depth texture).
zScaleBias = new Matrix4x4(
new Vector4(1.0f, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, 1.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, 0.5f, 0.0f),
new Vector4(0.0f, 0.0f, 0.5f, 1.0f)
);
}
screenToWorld[eyeIndex] = Matrix4x4.Inverse(toScreen * zScaleBias * gpuProj * view);
}
cmd.SetGlobalMatrixArray(ShaderConstants._ScreenToWorld, screenToWorld);
}
void PrecomputeLights(
out NativeArray<ushort> stencilVisLights,
out NativeArray<ushort> stencilVisLightOffsets,
ref NativeArray<VisibleLight> visibleLights,
bool hasAdditionalLights)
{
const int lightTypeCount = (int)LightType.Tube + 1;
if (!hasAdditionalLights)
{
stencilVisLights = new NativeArray<ushort>(0, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
stencilVisLightOffsets = new NativeArray<ushort>(lightTypeCount, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
for (int i = 0; i < lightTypeCount; ++i)
stencilVisLightOffsets[i] = k_InvalidLightOffset;
return;
}
NativeArray<int> stencilLightCounts = new NativeArray<int>(lightTypeCount, Allocator.Temp, NativeArrayOptions.ClearMemory);
stencilVisLightOffsets = new NativeArray<ushort>(lightTypeCount, Allocator.Temp, NativeArrayOptions.ClearMemory);
// Count the number of lights per type.
int visibleLightCount = visibleLights.Length;
for (ushort visLightIndex = 0; visLightIndex < visibleLightCount; ++visLightIndex)
{
ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex);
++stencilVisLightOffsets[(int)vl.lightType];
}
int totalStencilLightCount = stencilVisLightOffsets[(int)LightType.Spot] + stencilVisLightOffsets[(int)LightType.Directional] + stencilVisLightOffsets[(int)LightType.Point];
stencilVisLights = new NativeArray<ushort>(totalStencilLightCount, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
for (int i = 0, soffset = 0; i < stencilVisLightOffsets.Length; ++i)
{
if (stencilVisLightOffsets[i] == 0)
stencilVisLightOffsets[i] = k_InvalidLightOffset;
else
{
int c = stencilVisLightOffsets[i];
stencilVisLightOffsets[i] = (ushort)soffset;
soffset += c;
}
}
for (ushort visLightIndex = 0; visLightIndex < visibleLightCount; ++visLightIndex)
{
ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex);
if (vl.lightType != LightType.Spot &&
vl.lightType != LightType.Directional &&
vl.lightType != LightType.Point)
{
// The light type is not supported. Skip the light.
continue;
}
int i = stencilLightCounts[(int) vl.lightType]++;
stencilVisLights[stencilVisLightOffsets[(int) vl.lightType] + i] = visLightIndex;
}
stencilLightCounts.Dispose();
}
bool HasStencilLightsOfType(LightType type)
{
return m_stencilVisLightOffsets[(int)type] != k_InvalidLightOffset;
}
void RenderStencilLights(RasterCommandBuffer cmd, UniversalLightData lightData, UniversalShadowData shadowData, bool stripShadowsOffVariants)
{
if (m_stencilVisLights.Length == 0)
return;
if (m_StencilDeferredMaterial == null)
{
Debug.LogErrorFormat("Missing {0}. {1} render pass will not execute. Check for missing reference in the renderer resources.", m_StencilDeferredMaterial, GetType().Name);
return;
}
Profiler.BeginSample(k_DeferredStencilPass);
using (new ProfilingScope(cmd, m_ProfilingSamplerDeferredStencilPass))
{
NativeArray<VisibleLight> visibleLights = lightData.visibleLights;
bool hasLightCookieManager = m_LightCookieManager != null;
bool hasAdditionalLightPass = m_AdditionalLightsShadowCasterPass != null;
if (HasStencilLightsOfType(LightType.Directional))
RenderStencilDirectionalLights(cmd, stripShadowsOffVariants, lightData, shadowData, visibleLights, hasAdditionalLightPass, hasLightCookieManager, lightData.mainLightIndex);
if (lightData.supportsAdditionalLights)
{
if (HasStencilLightsOfType(LightType.Point))
RenderStencilPointLights(cmd, stripShadowsOffVariants, lightData, shadowData, visibleLights, hasAdditionalLightPass, hasLightCookieManager);
if (HasStencilLightsOfType(LightType.Spot))
RenderStencilSpotLights(cmd, stripShadowsOffVariants, lightData, shadowData, visibleLights, hasAdditionalLightPass, hasLightCookieManager);
}
}
Profiler.EndSample();
}
void RenderStencilDirectionalLights(RasterCommandBuffer cmd, bool stripShadowsOffVariants, UniversalLightData lightData, UniversalShadowData shadowData, NativeArray<VisibleLight> visibleLights, bool hasAdditionalLightPass, bool hasLightCookieManager, int mainLightIndex)
{
if (m_FullscreenMesh == null)
m_FullscreenMesh = CreateFullscreenMesh();
cmd.SetKeyword(ShaderGlobalKeywords._DIRECTIONAL, true);
// TODO bundle extra directional lights rendering by batches of 8.
// Also separate shadow caster lights from non-shadow caster.
int lastLightCookieIndex = -1;
bool isFirstLight = true;
bool lastLightCookieKeywordState = false;
bool lastShadowsKeywordState = false;
bool lastSoftShadowsKeywordState = false;
for (int soffset = m_stencilVisLightOffsets[(int)LightType.Directional]; soffset < m_stencilVisLights.Length; ++soffset)
{
ushort visLightIndex = m_stencilVisLights[soffset];
ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex);
if (vl.lightType != LightType.Directional)
break;
// Avoid light find on every access.
Light light = vl.light;
Vector4 lightDir, lightColor, lightAttenuation, lightSpotDir, lightOcclusionChannel;
UniversalRenderPipeline.InitializeLightConstants_Common(visibleLights, visLightIndex, out lightDir, out lightColor, out lightAttenuation, out lightSpotDir, out lightOcclusionChannel);
int lightFlags = 0;
if (light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed)
lightFlags |= (int)LightFlag.SubtractiveMixedLighting;
if (lightData.supportsLightLayers)
SetRenderingLayersMask(cmd, light, ShaderConstants._LightLayerMask);
// Setup shadow parameters:
// - for the main light, they have already been setup globally, so nothing to do.
// - for other directional lights, it is actually not supported by URP, but the code would look like this.
bool hasDeferredShadows = light && light.shadows != LightShadows.None;
bool isMainLight = visLightIndex == mainLightIndex;
if (!isMainLight)
{
int shadowLightIndex = hasAdditionalLightPass ? m_AdditionalLightsShadowCasterPass.GetShadowLightIndexFromLightIndex(visLightIndex) : -1;
hasDeferredShadows = light && light.shadows != LightShadows.None && shadowLightIndex >= 0;
cmd.SetGlobalInt(ShaderConstants._ShadowLightIndex, shadowLightIndex);
SetLightCookiesKeyword(cmd, visLightIndex, hasLightCookieManager, isFirstLight, ref lastLightCookieKeywordState, ref lastLightCookieIndex);
}
// Update keywords states
SetAdditionalLightsShadowsKeyword(ref cmd, stripShadowsOffVariants, shadowData.additionalLightShadowsEnabled, hasDeferredShadows, isFirstLight, ref lastShadowsKeywordState);
SetSoftShadowsKeyword(cmd, shadowData, light, hasDeferredShadows, isFirstLight, ref lastSoftShadowsKeywordState);
cmd.SetKeyword(ShaderGlobalKeywords._DEFERRED_FIRST_LIGHT, isFirstLight); // First directional light applies SSAO
cmd.SetKeyword(ShaderGlobalKeywords._DEFERRED_MAIN_LIGHT, isMainLight); // main directional light use different uniform constants from additional directional lights
// Update Global properties
cmd.SetGlobalVector(ShaderConstants._LightColor, lightColor); // VisibleLight.finalColor already returns color in active color space
cmd.SetGlobalVector(ShaderConstants._LightDirection, lightDir);
cmd.SetGlobalInt(ShaderConstants._LightFlags, lightFlags);
// Lighting pass.
cmd.DrawMesh(m_FullscreenMesh, Matrix4x4.identity, m_StencilDeferredMaterial, 0, m_StencilDeferredPasses[(int)StencilDeferredPasses.DirectionalLit]);
cmd.DrawMesh(m_FullscreenMesh, Matrix4x4.identity, m_StencilDeferredMaterial, 0, m_StencilDeferredPasses[(int)StencilDeferredPasses.DirectionalSimpleLit]);
isFirstLight = false;
}
cmd.SetKeyword(ShaderGlobalKeywords._DIRECTIONAL, false);
}
void RenderStencilPointLights(RasterCommandBuffer cmd, bool stripShadowsOffVariants, UniversalLightData lightData, UniversalShadowData shadowData, NativeArray<VisibleLight> visibleLights, bool hasAdditionalLightPass, bool hasLightCookieManager)
{
if (m_SphereMesh == null)
m_SphereMesh = CreateSphereMesh();
cmd.SetKeyword(ShaderGlobalKeywords._POINT, true);
int lastLightCookieIndex = -1;
bool isFirstLight = true;
bool lastLightCookieKeywordState = false;
bool lastShadowsKeywordState = false;
bool lastSoftShadowsKeywordState = false;
for (int soffset = m_stencilVisLightOffsets[(int)LightType.Point]; soffset < m_stencilVisLights.Length; ++soffset)
{
ushort visLightIndex = m_stencilVisLights[soffset];
ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex);
if (vl.lightType != LightType.Point)
break;
// Avoid light find on every access.
Light light = vl.light;
Vector3 posWS = vl.localToWorldMatrix.GetColumn(3);
Matrix4x4 transformMatrix = new Matrix4x4(
new Vector4(vl.range, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, vl.range, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, vl.range, 0.0f),
new Vector4(posWS.x, posWS.y, posWS.z, 1.0f)
);
Vector4 lightPos, lightColor, lightAttenuation, lightOcclusionChannel;
UniversalRenderPipeline.InitializeLightConstants_Common(visibleLights, visLightIndex, out lightPos, out lightColor, out lightAttenuation, out _, out lightOcclusionChannel);
if (lightData.supportsLightLayers)
SetRenderingLayersMask(cmd, light, ShaderConstants._LightLayerMask);
int lightFlags = 0;
if (light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed)
lightFlags |= (int)LightFlag.SubtractiveMixedLighting;
// Determine whether the light is casting shadows and what the index it should use.
int shadowLightIndex = hasAdditionalLightPass ? m_AdditionalLightsShadowCasterPass.GetShadowLightIndexFromLightIndex(visLightIndex) : -1;
bool hasDeferredShadows = light && light.shadows != LightShadows.None && shadowLightIndex >= 0;
// Update keywords states
SetAdditionalLightsShadowsKeyword(ref cmd, stripShadowsOffVariants, shadowData.additionalLightShadowsEnabled, hasDeferredShadows, isFirstLight, ref lastShadowsKeywordState);
SetSoftShadowsKeyword(cmd, shadowData, light, hasDeferredShadows, isFirstLight, ref lastSoftShadowsKeywordState);
SetLightCookiesKeyword(cmd, visLightIndex, hasLightCookieManager, isFirstLight, ref lastLightCookieKeywordState, ref lastLightCookieIndex);
// Update Global properties
cmd.SetGlobalVector(ShaderConstants._LightPosWS, lightPos);
cmd.SetGlobalVector(ShaderConstants._LightColor, lightColor);
cmd.SetGlobalVector(ShaderConstants._LightAttenuation, lightAttenuation);
cmd.SetGlobalVector(ShaderConstants._LightOcclusionProbInfo, lightOcclusionChannel);
cmd.SetGlobalInt(ShaderConstants._LightFlags, lightFlags);
cmd.SetGlobalInt(ShaderConstants._ShadowLightIndex, shadowLightIndex);
// Stencil pass.
cmd.DrawMesh(m_SphereMesh, transformMatrix, m_StencilDeferredMaterial, 0, m_StencilDeferredPasses[(int)StencilDeferredPasses.StencilVolume]);
// Lighting pass.
cmd.DrawMesh(m_SphereMesh, transformMatrix, m_StencilDeferredMaterial, 0, m_StencilDeferredPasses[(int)StencilDeferredPasses.PunctualLit]);
cmd.DrawMesh(m_SphereMesh, transformMatrix, m_StencilDeferredMaterial, 0, m_StencilDeferredPasses[(int)StencilDeferredPasses.PunctualSimpleLit]);
isFirstLight = false;
}
cmd.SetKeyword(ShaderGlobalKeywords._POINT, false);
}
void RenderStencilSpotLights(RasterCommandBuffer cmd, bool stripShadowsOffVariants, UniversalLightData lightData, UniversalShadowData shadowData, NativeArray<VisibleLight> visibleLights, bool hasAdditionalLightPass, bool hasLightCookieManager)
{
if (m_HemisphereMesh == null)
m_HemisphereMesh = CreateHemisphereMesh();
cmd.SetKeyword(ShaderGlobalKeywords._SPOT, true);
int lastLightCookieIndex = -1;
bool isFirstLight = true;
bool lastLightCookieKeywordState = false;
bool lastShadowsKeywordState = false;
bool lastSoftShadowsKeywordState = false;
for (int soffset = m_stencilVisLightOffsets[(int)LightType.Spot]; soffset < m_stencilVisLights.Length; ++soffset)
{
ushort visLightIndex = m_stencilVisLights[soffset];
ref VisibleLight vl = ref visibleLights.UnsafeElementAtMutable(visLightIndex);