-
Notifications
You must be signed in to change notification settings - Fork 777
/
VolumetricLighting.cs
1035 lines (823 loc) · 48.3 KB
/
VolumetricLighting.cs
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.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering.HighDefinition
{
// Optimized version of 'LocalVolumetricFogArtistParameters'.
// TODO: pack better. This data structure contains a bunch of UNORMs.
[GenerateHLSL]
struct LocalVolumetricFogEngineData
{
public Vector3 scattering; // [0, 1]
public float extinction; // [0, 1]
public Vector3 textureTiling;
public int invertFade; // bool...
public Vector3 textureScroll;
public float rcpDistFadeLen;
public Vector3 rcpPosFaceFade;
public float endTimesRcpDistFadeLen;
public Vector3 rcpNegFaceFade;
public int useVolumeMask; // bool
public Vector3 atlasOffset; // coordinates in the atlas in pixels
public LocalVolumetricFogFalloffMode falloffMode;
public Vector4 maskSize; // xyz: atlas size / mask size, w: mask size in pixels
public static LocalVolumetricFogEngineData GetNeutralValues()
{
LocalVolumetricFogEngineData data;
data.scattering = Vector3.zero;
data.extinction = 0;
data.atlasOffset = Vector3.zero;
data.textureTiling = Vector3.one;
data.textureScroll = Vector3.zero;
data.rcpPosFaceFade = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
data.rcpNegFaceFade = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
data.invertFade = 0;
data.rcpDistFadeLen = 0;
data.endTimesRcpDistFadeLen = 1;
data.useVolumeMask = 0;
data.maskSize = Vector4.zero;
data.falloffMode = LocalVolumetricFogFalloffMode.Linear;
return data;
}
} // struct VolumeProperties
[GenerateHLSL(needAccessors = false, generateCBuffer = true)]
unsafe struct ShaderVariablesVolumetric
{
[HLSLArray(ShaderConfig.k_XRMaxViewsForCBuffer, typeof(Matrix4x4))]
public fixed float _VBufferCoordToViewDirWS[ShaderConfig.k_XRMaxViewsForCBuffer * 16];
public float _VBufferUnitDepthTexelSpacing;
public uint _NumVisibleLocalVolumetricFog;
public float _CornetteShanksConstant;
public uint _VBufferHistoryIsValid;
public Vector4 _VBufferSampleOffset;
public Vector4 _VolumeMaskDimensions;
[HLSLArray(7, typeof(Vector4))]
public fixed float _AmbientProbeCoeffs[7 * 4]; // 3 bands of SH, packed, rescaled and convolved with the phase function
public float _VBufferVoxelSize;
public float _HaveToPad;
public float _OtherwiseTheBuffer;
public float _IsFilledWithGarbage;
public Vector4 _VBufferPrevViewportSize;
public Vector4 _VBufferHistoryViewportScale;
public Vector4 _VBufferHistoryViewportLimit;
public Vector4 _VBufferPrevDistanceEncodingParams;
public Vector4 _VBufferPrevDistanceDecodingParams;
// TODO: Remove if equals to the ones in global CB?
public uint _NumTileBigTileX;
public uint _NumTileBigTileY;
public uint _Pad0_SVV;
public uint _Pad1_SVV;
}
/// <summary></summary>
[GenerateHLSL]
public enum LocalVolumetricFogFalloffMode
{
/// <summary></summary>
Linear,
/// <summary></summary>
Exponential,
}
class VolumeRenderingUtils
{
public static float MeanFreePathFromExtinction(float extinction)
{
return 1.0f / extinction;
}
public static float ExtinctionFromMeanFreePath(float meanFreePath)
{
return 1.0f / meanFreePath;
}
public static Vector3 AbsorptionFromExtinctionAndScattering(float extinction, Vector3 scattering)
{
return new Vector3(extinction, extinction, extinction) - scattering;
}
public static Vector3 ScatteringFromExtinctionAndAlbedo(float extinction, Vector3 albedo)
{
return extinction * albedo;
}
public static Vector3 AlbedoFromMeanFreePathAndScattering(float meanFreePath, Vector3 scattering)
{
return meanFreePath * scattering;
}
}
struct LocalVolumetricFogList
{
public List<OrientedBBox> bounds;
public List<LocalVolumetricFogEngineData> density;
}
struct VBufferParameters
{
public Vector3Int viewportSize;
public float voxelSize;
public Vector4 depthEncodingParams;
public Vector4 depthDecodingParams;
public VBufferParameters(Vector3Int viewportSize, float depthExtent, float camNear, float camFar, float camVFoV,
float sliceDistributionUniformity, float voxelSize)
{
this.viewportSize = viewportSize;
this.voxelSize = voxelSize;
// The V-Buffer is sphere-capped, while the camera frustum is not.
// We always start from the near plane of the camera.
float aspectRatio = viewportSize.x / (float)viewportSize.y;
float farPlaneHeight = 2.0f * Mathf.Tan(0.5f * camVFoV) * camFar;
float farPlaneWidth = farPlaneHeight * aspectRatio;
float farPlaneMaxDim = Mathf.Max(farPlaneWidth, farPlaneHeight);
float farPlaneDist = Mathf.Sqrt(camFar * camFar + 0.25f * farPlaneMaxDim * farPlaneMaxDim);
float nearDist = camNear;
float farDist = Math.Min(nearDist + depthExtent, farPlaneDist);
float c = 2 - 2 * sliceDistributionUniformity; // remap [0, 1] -> [2, 0]
c = Mathf.Max(c, 0.001f); // Avoid NaNs
depthEncodingParams = ComputeLogarithmicDepthEncodingParams(nearDist, farDist, c);
depthDecodingParams = ComputeLogarithmicDepthDecodingParams(nearDist, farDist, c);
}
internal Vector3 ComputeViewportScale(Vector3Int bufferSize)
{
return new Vector3(HDUtils.ComputeViewportScale(viewportSize.x, bufferSize.x),
HDUtils.ComputeViewportScale(viewportSize.y, bufferSize.y),
HDUtils.ComputeViewportScale(viewportSize.z, bufferSize.z));
}
internal Vector3 ComputeViewportLimit(Vector3Int bufferSize)
{
return new Vector3(HDUtils.ComputeViewportLimit(viewportSize.x, bufferSize.x),
HDUtils.ComputeViewportLimit(viewportSize.y, bufferSize.y),
HDUtils.ComputeViewportLimit(viewportSize.z, bufferSize.z));
}
internal float ComputeLastSliceDistance(uint sliceCount)
{
float d = 1.0f - 0.5f / sliceCount;
float ln2 = 0.69314718f;
// DecodeLogarithmicDepthGeneralized(1 - 0.5 / sliceCount)
return depthDecodingParams.x * Mathf.Exp(ln2 * d * depthDecodingParams.y) + depthDecodingParams.z;
}
// See EncodeLogarithmicDepthGeneralized().
static Vector4 ComputeLogarithmicDepthEncodingParams(float nearPlane, float farPlane, float c)
{
Vector4 depthParams = new Vector4();
float n = nearPlane;
float f = farPlane;
depthParams.y = 1.0f / Mathf.Log(c * (f - n) + 1, 2);
depthParams.x = Mathf.Log(c, 2) * depthParams.y;
depthParams.z = n - 1.0f / c; // Same
depthParams.w = 0.0f;
return depthParams;
}
// See DecodeLogarithmicDepthGeneralized().
static Vector4 ComputeLogarithmicDepthDecodingParams(float nearPlane, float farPlane, float c)
{
Vector4 depthParams = new Vector4();
float n = nearPlane;
float f = farPlane;
depthParams.x = 1.0f / c;
depthParams.y = Mathf.Log(c * (f - n) + 1, 2);
depthParams.z = n - 1.0f / c; // Same
depthParams.w = 0.0f;
return depthParams;
}
}
public partial class HDRenderPipeline
{
ComputeShader m_VolumeVoxelizationCS = null;
ComputeShader m_VolumetricLightingCS = null;
ComputeShader m_VolumetricLightingFilteringCS = null;
List<OrientedBBox> m_VisibleVolumeBounds = null;
List<LocalVolumetricFogEngineData> m_VisibleVolumeData = null;
internal const int k_MaxVisibleLocalVolumetricFogCount = 512;
// Static keyword is required here else we get a "DestroyBuffer can only be called from the main thread"
ComputeBuffer m_VisibleVolumeBoundsBuffer = null;
ComputeBuffer m_VisibleVolumeDataBuffer = null;
ShaderVariablesVolumetric m_ShaderVariablesVolumetricCB = new ShaderVariablesVolumetric();
// This size is shared between all cameras to create the volumetric 3D textures
static Vector3Int s_CurrentVolumetricBufferSize;
// Is the feature globally disabled?
bool m_SupportVolumetrics = false;
Vector4[] m_PackedCoeffs;
ZonalHarmonicsL2 m_PhaseZH;
Vector2[] m_xySeq;
// This is a sequence of 7 equidistant numbers from 1/14 to 13/14.
// Each of them is the centroid of the interval of length 2/14.
// They've been rearranged in a sequence of pairs {small, large}, s.t. (small + large) = 1.
// That way, the running average position is close to 0.5.
// | 6 | 2 | 4 | 1 | 5 | 3 | 7 |
// | | | | o | | | |
// | | o | | x | | | |
// | | x | | x | | o | |
// | | x | o | x | | x | |
// | | x | x | x | o | x | |
// | o | x | x | x | x | x | |
// | x | x | x | x | x | x | o |
// | x | x | x | x | x | x | x |
float[] m_zSeq = { 7.0f / 14.0f, 3.0f / 14.0f, 11.0f / 14.0f, 5.0f / 14.0f, 9.0f / 14.0f, 1.0f / 14.0f, 13.0f / 14.0f };
Matrix4x4[] m_PixelCoordToViewDirWS;
static internal void SafeDestroy(ref RenderTexture rt)
{
if (rt != null)
{
rt.Release(); // The texture itself is not destroyed: https://docs.unity3d.com/ScriptReference/RenderTexture.Release.html
Object.DestroyImmediate(rt); // Destroy() may not be called from the Edit mode
}
}
static uint VolumetricFrameIndex(HDCamera hdCamera)
{
// Here we do modulo 14 because we need the enable to detect a change every frame, but the accumulation is done on 7 frames (7x2=14)
return hdCamera.GetCameraFrameCount() % 14;
}
static internal Vector3Int ComputeVolumetricViewportSize(HDCamera hdCamera, ref float voxelSize)
{
var controller = hdCamera.volumeStack.GetComponent<Fog>();
Debug.Assert(controller != null);
int viewportWidth = hdCamera.actualWidth;
int viewportHeight = hdCamera.actualHeight;
float screenFraction;
int sliceCount;
if (controller.fogControlMode == FogControl.Balance)
{
// Evaluate the ssFraction and sliceCount based on the control parameters
float maxScreenSpaceFraction = (1.0f - controller.resolutionDepthRatio) * (Fog.maxFogScreenResolutionPercentage - Fog.minFogScreenResolutionPercentage) + Fog.minFogScreenResolutionPercentage;
screenFraction = Mathf.Lerp(Fog.minFogScreenResolutionPercentage, maxScreenSpaceFraction, controller.volumetricFogBudget) * 0.01f;
float maxSliceCount = Mathf.Max(1.0f, controller.resolutionDepthRatio * Fog.maxFogSliceCount);
sliceCount = (int)Mathf.Lerp(1.0f, maxSliceCount, controller.volumetricFogBudget);
// Evaluate the voxel size
voxelSize = 1.0f / screenFraction;
}
else
{
screenFraction = controller.screenResolutionPercentage.value * 0.01f;
sliceCount = controller.volumeSliceCount.value;
if (controller.screenResolutionPercentage.value == Fog.optimalFogScreenResolutionPercentage)
voxelSize = 8;
else
voxelSize = 1.0f / screenFraction; // Does not account for rounding (same function, above)
}
int w = Mathf.RoundToInt(viewportWidth * screenFraction);
int h = Mathf.RoundToInt(viewportHeight * screenFraction);
// Round to nearest multiple of viewCount so that each views have the exact same number of slices (important for XR)
int d = hdCamera.viewCount * Mathf.CeilToInt(sliceCount / hdCamera.viewCount);
return new Vector3Int(w, h, d);
}
static internal VBufferParameters ComputeVolumetricBufferParameters(HDCamera hdCamera)
{
var controller = hdCamera.volumeStack.GetComponent<Fog>();
Debug.Assert(controller != null);
float voxelSize = 0;
Vector3Int viewportSize = ComputeVolumetricViewportSize(hdCamera, ref voxelSize);
return new VBufferParameters(viewportSize, controller.depthExtent.value,
hdCamera.camera.nearClipPlane,
hdCamera.camera.farClipPlane,
hdCamera.camera.fieldOfView,
controller.sliceDistributionUniformity.value,
voxelSize);
}
static internal void ReinitializeVolumetricBufferParams(HDCamera hdCamera)
{
if (!Fog.IsVolumetricFogEnabled(hdCamera))
return;
bool fog = Fog.IsVolumetricFogEnabled(hdCamera);
bool init = hdCamera.vBufferParams != null;
if (fog ^ init)
{
if (init)
{
// Deinitialize.
hdCamera.vBufferParams = null;
}
else
{
// Initialize.
// Start with the same parameters for both frames. Then update them one by one every frame.
var parameters = ComputeVolumetricBufferParameters(hdCamera);
hdCamera.vBufferParams = new VBufferParameters[2];
hdCamera.vBufferParams[0] = parameters;
hdCamera.vBufferParams[1] = parameters;
}
}
}
// This function relies on being called once per camera per frame.
// The results are undefined otherwise.
static internal void UpdateVolumetricBufferParams(HDCamera hdCamera)
{
if (!Fog.IsVolumetricFogEnabled(hdCamera))
return;
Debug.Assert(hdCamera.vBufferParams != null);
Debug.Assert(hdCamera.vBufferParams.Length == 2);
var currentParams = ComputeVolumetricBufferParameters(hdCamera);
int frameIndex = (int)VolumetricFrameIndex(hdCamera);
var currIdx = (frameIndex + 0) & 1;
var prevIdx = (frameIndex + 1) & 1;
hdCamera.vBufferParams[currIdx] = currentParams;
// Handle case of first frame. When we are on the first frame, we reuse the value of original frame.
if (hdCamera.vBufferParams[prevIdx].viewportSize.x == 0.0f && hdCamera.vBufferParams[prevIdx].viewportSize.y == 0.0f)
{
hdCamera.vBufferParams[prevIdx] = currentParams;
}
// Update size used to create volumetric buffers.
s_CurrentVolumetricBufferSize = new Vector3Int(Math.Max(s_CurrentVolumetricBufferSize.x, currentParams.viewportSize.x),
Math.Max(s_CurrentVolumetricBufferSize.y, currentParams.viewportSize.y),
Math.Max(s_CurrentVolumetricBufferSize.z, currentParams.viewportSize.z));
}
// Do not access 'rt.name', it allocates memory every time...
// Have to manually cache and pass the name.
static internal void ResizeVolumetricBuffer(ref RTHandle rt, string name, int viewportWidth, int viewportHeight, int viewportDepth)
{
Debug.Assert(rt != null);
int width = rt.rt.width;
int height = rt.rt.height;
int depth = rt.rt.volumeDepth;
bool realloc = (width < viewportWidth) || (height < viewportHeight) || (depth < viewportDepth);
if (realloc)
{
RTHandles.Release(rt);
width = Math.Max(width, viewportWidth);
height = Math.Max(height, viewportHeight);
depth = Math.Max(depth, viewportDepth);
rt = RTHandles.Alloc(width, height, depth, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, // 8888_sRGB is not precise enough
dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: name);
}
}
struct GenerateMaxZParameters
{
public ComputeShader generateMaxZCS;
public int maxZKernel;
public int maxZDownsampleKernel;
public int dilateMaxZKernel;
public Vector2Int intermediateMaskSize;
public Vector2Int finalMaskSize;
public Vector2Int minDepthMipOffset;
public float dilationWidth;
public int viewCount;
}
GenerateMaxZParameters PrepareGenerateMaxZParameters(HDCamera hdCamera, HDUtils.PackedMipChainInfo depthMipInfo)
{
var parameters = new GenerateMaxZParameters();
parameters.generateMaxZCS = defaultResources.shaders.maxZCS;
parameters.maxZKernel = parameters.generateMaxZCS.FindKernel("ComputeMaxZ");
parameters.maxZDownsampleKernel = parameters.generateMaxZCS.FindKernel("ComputeFinalMask");
parameters.dilateMaxZKernel = parameters.generateMaxZCS.FindKernel("DilateMask");
parameters.intermediateMaskSize.x = HDUtils.DivRoundUp(hdCamera.actualWidth, 8);
parameters.intermediateMaskSize.y = HDUtils.DivRoundUp(hdCamera.actualHeight, 8);
parameters.finalMaskSize.x = parameters.intermediateMaskSize.x / 2;
parameters.finalMaskSize.y = parameters.intermediateMaskSize.y / 2;
parameters.minDepthMipOffset.x = depthMipInfo.mipLevelOffsets[4].x;
parameters.minDepthMipOffset.y = depthMipInfo.mipLevelOffsets[4].y;
int frameIndex = (int)VolumetricFrameIndex(hdCamera);
var currIdx = frameIndex & 1;
var currentParams = hdCamera.vBufferParams[currIdx];
float ratio = (float)currentParams.viewportSize.x / (float)hdCamera.actualWidth;
parameters.dilationWidth = ratio < 0.1f ? 2 :
ratio < 0.5f ? 1 : 0;
parameters.viewCount = hdCamera.viewCount;
return parameters;
}
static void GenerateMaxZ(in GenerateMaxZParameters parameters, RTHandle depthTexture, RTHandle maxZ8x, RTHandle maxZ, RTHandle dilatedMaxZ, CommandBuffer cmd)
{
// --------------------------------------------------------------
// Downsample 8x8 with max operator
var cs = parameters.generateMaxZCS;
var kernel = parameters.maxZKernel;
int maskW = parameters.intermediateMaskSize.x;
int maskH = parameters.intermediateMaskSize.y;
int dispatchX = maskW;
int dispatchY = maskH;
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._OutputTexture, maxZ8x);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._CameraDepthTexture, depthTexture);
cmd.DispatchCompute(cs, kernel, dispatchX, dispatchY, parameters.viewCount);
// --------------------------------------------------------------
// Downsample to 16x16 and compute gradient if required
kernel = parameters.maxZDownsampleKernel;
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._InputTexture, maxZ8x);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._OutputTexture, maxZ);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._CameraDepthTexture, depthTexture);
Vector4 srcLimitAndDepthOffset = new Vector4(
maskW,
maskH,
parameters.minDepthMipOffset.x,
parameters.minDepthMipOffset.y
);
cmd.SetComputeVectorParam(cs, HDShaderIDs._SrcOffsetAndLimit, srcLimitAndDepthOffset);
cmd.SetComputeFloatParam(cs, HDShaderIDs._DilationWidth, parameters.dilationWidth);
int finalMaskW = maskW / 2;
int finalMaskH = maskH / 2;
dispatchX = HDUtils.DivRoundUp(finalMaskW, 8);
dispatchY = HDUtils.DivRoundUp(finalMaskH, 8);
cmd.DispatchCompute(cs, kernel, dispatchX, dispatchY, parameters.viewCount);
// --------------------------------------------------------------
// Dilate max Z and gradient.
kernel = parameters.dilateMaxZKernel;
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._InputTexture, maxZ);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._OutputTexture, dilatedMaxZ);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._CameraDepthTexture, depthTexture);
srcLimitAndDepthOffset.x = finalMaskW;
srcLimitAndDepthOffset.y = finalMaskH;
cmd.SetComputeVectorParam(cs, HDShaderIDs._SrcOffsetAndLimit, srcLimitAndDepthOffset);
cmd.DispatchCompute(cs, kernel, dispatchX, dispatchY, parameters.viewCount);
}
static internal void CreateVolumetricHistoryBuffers(HDCamera hdCamera, int bufferCount)
{
if (!Fog.IsVolumetricFogEnabled(hdCamera))
return;
Debug.Assert(hdCamera.volumetricHistoryBuffers == null);
hdCamera.volumetricHistoryBuffers = new RTHandle[bufferCount];
// Allocation happens early in the frame. So we shouldn't rely on 'hdCamera.vBufferParams'.
// Allocate the smallest possible 3D texture.
// We will perform rescaling manually, in a custom manner, based on volume parameters.
const int minSize = 4;
for (int i = 0; i < bufferCount; i++)
{
hdCamera.volumetricHistoryBuffers[i] = RTHandles.Alloc(minSize, minSize, minSize, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, // 8888_sRGB is not precise enough
dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: string.Format("VBufferHistory{0}", i));
}
hdCamera.volumetricHistoryIsValid = false;
}
static internal void DestroyVolumetricHistoryBuffers(HDCamera hdCamera)
{
if (hdCamera.volumetricHistoryBuffers == null)
return;
int bufferCount = hdCamera.volumetricHistoryBuffers.Length;
for (int i = 0; i < bufferCount; i++)
{
RTHandles.Release(hdCamera.volumetricHistoryBuffers[i]);
}
hdCamera.volumetricHistoryBuffers = null;
hdCamera.volumetricHistoryIsValid = false;
}
// Must be called AFTER UpdateVolumetricBufferParams.
static readonly string[] volumetricHistoryBufferNames = new string[2] { "VBufferHistory0", "VBufferHistory1" };
static internal void ResizeVolumetricHistoryBuffers(HDCamera hdCamera)
{
if (!hdCamera.IsVolumetricReprojectionEnabled())
return;
Debug.Assert(hdCamera.vBufferParams != null);
Debug.Assert(hdCamera.vBufferParams.Length == 2);
Debug.Assert(hdCamera.volumetricHistoryBuffers != null);
int frameIndex = (int)VolumetricFrameIndex(hdCamera);
var currIdx = (frameIndex + 0) & 1;
var prevIdx = (frameIndex + 1) & 1;
var currentParams = hdCamera.vBufferParams[currIdx];
// Render texture contents can become "lost" on certain events, like loading a new level,
// system going to a screensaver mode, in and out of fullscreen and so on.
// https://docs.unity3d.com/ScriptReference/RenderTexture.html
if (hdCamera.volumetricHistoryBuffers[0] == null || hdCamera.volumetricHistoryBuffers[1] == null)
{
DestroyVolumetricHistoryBuffers(hdCamera);
CreateVolumetricHistoryBuffers(hdCamera, hdCamera.vBufferParams.Length); // Basically, assume it's 2
}
// We only resize the feedback buffer (#0), not the history buffer (#1).
// We must NOT resize the buffer from the previous frame (#1), as that would invalidate its contents.
ResizeVolumetricBuffer(ref hdCamera.volumetricHistoryBuffers[currIdx], volumetricHistoryBufferNames[currIdx], currentParams.viewportSize.x,
currentParams.viewportSize.y,
currentParams.viewportSize.z);
}
internal void CreateVolumetricLightingBuffers()
{
Debug.Assert(m_VolumetricLightingCS != null);
m_VisibleVolumeBounds = new List<OrientedBBox>();
m_VisibleVolumeData = new List<LocalVolumetricFogEngineData>();
m_VisibleVolumeBoundsBuffer = new ComputeBuffer(k_MaxVisibleLocalVolumetricFogCount, Marshal.SizeOf(typeof(OrientedBBox)));
m_VisibleVolumeDataBuffer = new ComputeBuffer(k_MaxVisibleLocalVolumetricFogCount, Marshal.SizeOf(typeof(LocalVolumetricFogEngineData)));
}
internal void DestroyVolumetricLightingBuffers()
{
CoreUtils.SafeRelease(m_VisibleVolumeDataBuffer);
CoreUtils.SafeRelease(m_VisibleVolumeBoundsBuffer);
m_VisibleVolumeData = null; // free()
m_VisibleVolumeBounds = null; // free()
}
void InitializeVolumetricLighting()
{
m_SupportVolumetrics = asset.currentPlatformRenderPipelineSettings.supportVolumetrics;
if (!m_SupportVolumetrics)
return;
m_VolumeVoxelizationCS = defaultResources.shaders.volumeVoxelizationCS;
m_VolumetricLightingCS = defaultResources.shaders.volumetricLightingCS;
m_VolumetricLightingFilteringCS = defaultResources.shaders.volumetricLightingFilteringCS;
m_PackedCoeffs = new Vector4[7];
m_PhaseZH = new ZonalHarmonicsL2();
m_PhaseZH.coeffs = new float[3];
m_xySeq = new Vector2[7];
m_PixelCoordToViewDirWS = new Matrix4x4[ShaderConfig.s_XrMaxViews];
CreateVolumetricLightingBuffers();
}
void CleanupVolumetricLighting()
{
DestroyVolumetricLightingBuffers();
m_VolumeVoxelizationCS = null;
m_VolumetricLightingCS = null;
m_VolumetricLightingFilteringCS = null;
}
static float CornetteShanksPhasePartConstant(float anisotropy)
{
float g = anisotropy;
return (3.0f / (8.0f * Mathf.PI)) * (1.0f - g * g) / (2.0f + g * g);
}
void UpdateShaderVariablesGlobalVolumetrics(ref ShaderVariablesGlobal cb, HDCamera hdCamera)
{
if (!Fog.IsVolumetricFogEnabled(hdCamera))
{
return;
}
// Get the interpolated anisotropy value.
var fog = hdCamera.volumeStack.GetComponent<Fog>();
uint frameIndex = hdCamera.GetCameraFrameCount();
uint currIdx = (frameIndex + 0) & 1;
var currParams = hdCamera.vBufferParams[currIdx];
// The lighting & density buffers are shared by all cameras.
// The history & feedback buffers are specific to the camera.
// These 2 types of buffers can have different sizes.
// Additionally, history buffers can have different sizes, since they are not resized at the same time.
var cvp = currParams.viewportSize;
// Adjust slices for XR rendering: VBuffer is shared for all single-pass views
uint sliceCount = (uint)(cvp.z / hdCamera.viewCount);
cb._VBufferViewportSize = new Vector4(cvp.x, cvp.y, 1.0f / cvp.x, 1.0f / cvp.y);
cb._VBufferSliceCount = sliceCount;
cb._VBufferRcpSliceCount = 1.0f / sliceCount;
cb._VBufferLightingViewportScale = currParams.ComputeViewportScale(s_CurrentVolumetricBufferSize);
cb._VBufferLightingViewportLimit = currParams.ComputeViewportLimit(s_CurrentVolumetricBufferSize);
cb._VBufferDistanceEncodingParams = currParams.depthEncodingParams;
cb._VBufferDistanceDecodingParams = currParams.depthDecodingParams;
cb._VBufferLastSliceDist = currParams.ComputeLastSliceDistance(sliceCount);
cb._VBufferRcpInstancedViewCount = 1.0f / hdCamera.viewCount;
}
LocalVolumetricFogList PrepareVisibleLocalVolumetricFogList(HDCamera hdCamera, CommandBuffer cmd)
{
LocalVolumetricFogList localVolumetricFog = new LocalVolumetricFogList();
if (!Fog.IsVolumetricFogEnabled(hdCamera))
return localVolumetricFog;
using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PrepareVisibleLocalVolumetricFogList)))
{
Vector3 camPosition = hdCamera.camera.transform.position;
Vector3 camOffset = Vector3.zero;// World-origin-relative
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
camOffset = camPosition; // Camera-relative
}
m_VisibleVolumeBounds.Clear();
m_VisibleVolumeData.Clear();
// Collect all visible finite volume data, and upload it to the GPU.
var volumes = LocalVolumetricFogManager.manager.PrepareLocalVolumetricFogData(cmd, hdCamera);
for (int i = 0; i < Math.Min(volumes.Count, k_MaxVisibleLocalVolumetricFogCount); i++)
{
LocalVolumetricFog volume = volumes[i];
// TODO: cache these?
var obb = new OrientedBBox(Matrix4x4.TRS(volume.transform.position, volume.transform.rotation, volume.parameters.size));
// Handle camera-relative rendering.
obb.center -= camOffset;
// Frustum cull on the CPU for now. TODO: do it on the GPU.
// TODO: account for custom near and far planes of the V-Buffer's frustum.
// It's typically much shorter (along the Z axis) than the camera's frustum.
if (GeometryUtils.Overlap(obb, hdCamera.frustum, 6, 8))
{
// TODO: cache these?
var data = volume.parameters.ConvertToEngineData();
m_VisibleVolumeBounds.Add(obb);
m_VisibleVolumeData.Add(data);
}
}
m_VisibleVolumeBoundsBuffer.SetData(m_VisibleVolumeBounds);
m_VisibleVolumeDataBuffer.SetData(m_VisibleVolumeData);
// Fill the struct with pointers in order to share the data with the light loop.
localVolumetricFog.bounds = m_VisibleVolumeBounds;
localVolumetricFog.density = m_VisibleVolumeData;
return localVolumetricFog;
}
}
struct VolumeVoxelizationParameters
{
public ComputeShader voxelizationCS;
public int voxelizationKernel;
public Vector4 resolution;
public int viewCount;
public bool tiledLighting;
public Texture volumeAtlas;
public ShaderVariablesVolumetric volumetricCB;
public ShaderVariablesLightList lightListCB;
}
unsafe void SetPreconvolvedAmbientLightProbe(ref ShaderVariablesVolumetric cb, HDCamera hdCamera, Fog fog)
{
SphericalHarmonicsL2 probeSH = SphericalHarmonicMath.UndoCosineRescaling(m_SkyManager.GetAmbientProbe(hdCamera));
probeSH = SphericalHarmonicMath.RescaleCoefficients(probeSH, fog.globalLightProbeDimmer.value);
ZonalHarmonicsL2.GetCornetteShanksPhaseFunction(m_PhaseZH, fog.anisotropy.value);
SphericalHarmonicsL2 finalSH = SphericalHarmonicMath.PremultiplyCoefficients(SphericalHarmonicMath.Convolve(probeSH, m_PhaseZH));
SphericalHarmonicMath.PackCoefficients(m_PackedCoeffs, finalSH);
for (int i = 0; i < 7; i++)
for (int j = 0; j < 4; ++j)
cb._AmbientProbeCoeffs[i * 4 + j] = m_PackedCoeffs[i][j];
}
unsafe void UpdateShaderVariableslVolumetrics(ref ShaderVariablesVolumetric cb, HDCamera hdCamera, in Vector4 resolution)
{
var fog = hdCamera.volumeStack.GetComponent<Fog>();
var vFoV = hdCamera.camera.GetGateFittedFieldOfView() * Mathf.Deg2Rad;
var gpuAspect = HDUtils.ProjectionMatrixAspect(hdCamera.mainViewConstants.projMatrix);
int frameIndex = (int)VolumetricFrameIndex(hdCamera);
// Compose the matrix which allows us to compute the world space view direction.
hdCamera.GetPixelCoordToViewDirWS(resolution, gpuAspect, ref m_PixelCoordToViewDirWS);
for (int i = 0; i < m_PixelCoordToViewDirWS.Length; ++i)
for (int j = 0; j < 16; ++j)
cb._VBufferCoordToViewDirWS[i * 16 + j] = m_PixelCoordToViewDirWS[i][j];
cb._VBufferUnitDepthTexelSpacing = HDUtils.ComputZPlaneTexelSpacing(1.0f, vFoV, resolution.y);
cb._NumVisibleLocalVolumetricFog = (uint)m_VisibleVolumeBounds.Count;
cb._CornetteShanksConstant = CornetteShanksPhasePartConstant(fog.anisotropy.value);
cb._VBufferHistoryIsValid = hdCamera.volumetricHistoryIsValid ? 1u : 0u;
GetHexagonalClosePackedSpheres7(m_xySeq);
int sampleIndex = frameIndex % 7;
Vector4 xySeqOffset = new Vector4();
// TODO: should we somehow reorder offsets in Z based on the offset in XY? S.t. the samples more evenly cover the domain.
// Currently, we assume that they are completely uncorrelated, but maybe we should correlate them somehow.
xySeqOffset.Set(m_xySeq[sampleIndex].x, m_xySeq[sampleIndex].y, m_zSeq[sampleIndex], frameIndex);
cb._VBufferSampleOffset = xySeqOffset;
var volumeAtlas = LocalVolumetricFogManager.manager.volumeAtlas.GetAtlas();
cb._VolumeMaskDimensions = Vector4.zero;
if (LocalVolumetricFogManager.manager.volumeAtlas.GetAtlas() != null)
{
cb._VolumeMaskDimensions.x = volumeAtlas.width; // 1 / number of textures
cb._VolumeMaskDimensions.y = volumeAtlas.height;
cb._VolumeMaskDimensions.z = volumeAtlas.volumeDepth;
cb._VolumeMaskDimensions.w = 0; // Not used
}
SetPreconvolvedAmbientLightProbe(ref cb, hdCamera, fog);
var currIdx = (frameIndex + 0) & 1;
var prevIdx = (frameIndex + 1) & 1;
var currParams = hdCamera.vBufferParams[currIdx];
var prevParams = hdCamera.vBufferParams[prevIdx];
var pvp = prevParams.viewportSize;
// The lighting & density buffers are shared by all cameras.
// The history & feedback buffers are specific to the camera.
// These 2 types of buffers can have different sizes.
// Additionally, history buffers can have different sizes, since they are not resized at the same time.
Vector3Int historyBufferSize = Vector3Int.zero;
if (hdCamera.IsVolumetricReprojectionEnabled())
{
RTHandle historyRT = hdCamera.volumetricHistoryBuffers[prevIdx];
historyBufferSize = new Vector3Int(historyRT.rt.width, historyRT.rt.height, historyRT.rt.volumeDepth);
}
cb._VBufferVoxelSize = currParams.voxelSize;
cb._VBufferPrevViewportSize = new Vector4(pvp.x, pvp.y, 1.0f / pvp.x, 1.0f / pvp.y);
cb._VBufferHistoryViewportScale = prevParams.ComputeViewportScale(historyBufferSize);
cb._VBufferHistoryViewportLimit = prevParams.ComputeViewportLimit(historyBufferSize);
cb._VBufferPrevDistanceEncodingParams = prevParams.depthEncodingParams;
cb._VBufferPrevDistanceDecodingParams = prevParams.depthDecodingParams;
cb._NumTileBigTileX = (uint)GetNumTileBigTileX(hdCamera);
cb._NumTileBigTileY = (uint)GetNumTileBigTileY(hdCamera);
}
VolumeVoxelizationParameters PrepareVolumeVoxelizationParameters(HDCamera hdCamera)
{
var parameters = new VolumeVoxelizationParameters();
int frameIndex = (int)VolumetricFrameIndex(hdCamera);
var currIdx = (frameIndex + 0) & 1;
var prevIdx = (frameIndex + 1) & 1;
var currParams = hdCamera.vBufferParams[currIdx];
parameters.viewCount = hdCamera.viewCount;
parameters.tiledLighting = HasLightToCull() && hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass);
bool optimal = currParams.voxelSize == 8;
parameters.voxelizationCS = m_VolumeVoxelizationCS;
parameters.voxelizationKernel = (parameters.tiledLighting ? 1 : 0) | (!optimal ? 2 : 0);
var cvp = currParams.viewportSize;
parameters.resolution = new Vector4(cvp.x, cvp.y, 1.0f / cvp.x, 1.0f / cvp.y);
parameters.volumeAtlas = LocalVolumetricFogManager.manager.volumeAtlas.GetAtlas();
if (parameters.volumeAtlas == null)
{
parameters.volumeAtlas = CoreUtils.blackVolumeTexture;
}
UpdateShaderVariableslVolumetrics(ref m_ShaderVariablesVolumetricCB, hdCamera, parameters.resolution);
parameters.volumetricCB = m_ShaderVariablesVolumetricCB;
parameters.lightListCB = m_ShaderVariablesLightListCB;
return parameters;
}
static void VolumeVoxelizationPass(in VolumeVoxelizationParameters parameters,
RTHandle densityBuffer,
ComputeBuffer visibleVolumeBoundsBuffer,
ComputeBuffer visibleVolumeDataBuffer,
ComputeBuffer bigTileLightList,
CommandBuffer cmd)
{
if (parameters.tiledLighting)
cmd.SetComputeBufferParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs.g_vBigTileLightList, bigTileLightList);
cmd.SetComputeTextureParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VBufferDensity, densityBuffer);
cmd.SetComputeBufferParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeBounds, visibleVolumeBoundsBuffer);
cmd.SetComputeBufferParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeData, visibleVolumeDataBuffer);
cmd.SetComputeTextureParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeMaskAtlas, parameters.volumeAtlas);
ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesVolumetric);
ConstantBuffer.Set<ShaderVariablesLightList>(cmd, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesLightList);
// The shader defines GROUP_SIZE_1D = 8.
cmd.DispatchCompute(parameters.voxelizationCS, parameters.voxelizationKernel, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount);
}
// Ref: https://en.wikipedia.org/wiki/Close-packing_of_equal_spheres
// The returned {x, y} coordinates (and all spheres) are all within the (-0.5, 0.5)^2 range.
// The pattern has been rotated by 15 degrees to maximize the resolution along X and Y:
// https://www.desmos.com/calculator/kcpfvltz7c
static void GetHexagonalClosePackedSpheres7(Vector2[] coords)
{
float r = 0.17054068870105443882f;
float d = 2 * r;
float s = r * Mathf.Sqrt(3);
// Try to keep the weighted average as close to the center (0.5) as possible.
// (7)(5) ( )( ) ( )( ) ( )( ) ( )( ) ( )(o) ( )(x) (o)(x) (x)(x)
// (2)(1)(3) ( )(o)( ) (o)(x)( ) (x)(x)(o) (x)(x)(x) (x)(x)(x) (x)(x)(x) (x)(x)(x) (x)(x)(x)
// (4)(6) ( )( ) ( )( ) ( )( ) (o)( ) (x)( ) (x)(o) (x)(x) (x)(x)
coords[0] = new Vector2(0, 0);
coords[1] = new Vector2(-d, 0);
coords[2] = new Vector2(d, 0);
coords[3] = new Vector2(-r, -s);
coords[4] = new Vector2(r, s);
coords[5] = new Vector2(r, -s);
coords[6] = new Vector2(-r, s);
// Rotate the sampling pattern by 15 degrees.
const float cos15 = 0.96592582628906828675f;
const float sin15 = 0.25881904510252076235f;
for (int i = 0; i < 7; i++)
{
Vector2 coord = coords[i];
coords[i].x = coord.x * cos15 - coord.y * sin15;
coords[i].y = coord.x * sin15 + coord.y * cos15;
}
}
struct VolumetricLightingParameters
{
public ComputeShader volumetricLightingCS;
public ComputeShader volumetricLightingFilteringCS;
public int volumetricLightingKernel;
public int volumetricFilteringKernel;
public bool tiledLighting;
public Vector4 resolution;
public bool enableReprojection;
public int viewCount;
public int sliceCount;
public bool filterVolume;
public ShaderVariablesVolumetric volumetricCB;
public ShaderVariablesLightList lightListCB;
}
VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCamera)
{
var parameters = new VolumetricLightingParameters();
int frameIndex = (int)VolumetricFrameIndex(hdCamera);
var currIdx = (frameIndex + 0) & 1;
var prevIdx = (frameIndex + 1) & 1;
var currParams = hdCamera.vBufferParams[currIdx];
// Get the interpolated anisotropy value.
var fog = hdCamera.volumeStack.GetComponent<Fog>();
// Only available in the Play Mode because all the frame counters in the Edit Mode are broken.
parameters.tiledLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass);
bool volumeAllowsReprojection = ((int)fog.denoisingMode.value & (int)FogDenoisingMode.Reprojection) != 0;
parameters.enableReprojection = hdCamera.IsVolumetricReprojectionEnabled() && volumeAllowsReprojection;
bool enableAnisotropy = fog.anisotropy.value != 0;
// The multi-pass integration is only possible if re-projection is possible and the effect is not in anisotropic mode.
bool optimal = currParams.voxelSize == 8;
parameters.volumetricLightingCS = m_VolumetricLightingCS;
parameters.volumetricLightingFilteringCS = m_VolumetricLightingFilteringCS;
parameters.volumetricLightingCS.shaderKeywords = null;
CoreUtils.SetKeyword(parameters.volumetricLightingCS, "LIGHTLOOP_DISABLE_TILE_AND_CLUSTER", !parameters.tiledLighting);
CoreUtils.SetKeyword(parameters.volumetricLightingCS, "ENABLE_REPROJECTION", parameters.enableReprojection);
CoreUtils.SetKeyword(parameters.volumetricLightingCS, "ENABLE_ANISOTROPY", enableAnisotropy);
CoreUtils.SetKeyword(parameters.volumetricLightingCS, "VL_PRESET_OPTIMAL", optimal);
CoreUtils.SetKeyword(parameters.volumetricLightingCS, "SUPPORT_LOCAL_LIGHTS", !fog.directionalLightsOnly.value);
parameters.volumetricLightingKernel = parameters.volumetricLightingCS.FindKernel("VolumetricLighting");
parameters.volumetricFilteringKernel = parameters.volumetricLightingFilteringCS.FindKernel("FilterVolumetricLighting");
var cvp = currParams.viewportSize;
parameters.resolution = new Vector4(cvp.x, cvp.y, 1.0f / cvp.x, 1.0f / cvp.y);
parameters.viewCount = hdCamera.viewCount;
parameters.filterVolume = ((int)fog.denoisingMode.value & (int)FogDenoisingMode.Gaussian) != 0;
parameters.sliceCount = (int)(cvp.z);
UpdateShaderVariableslVolumetrics(ref m_ShaderVariablesVolumetricCB, hdCamera, parameters.resolution);
parameters.volumetricCB = m_ShaderVariablesVolumetricCB;
parameters.lightListCB = m_ShaderVariablesLightListCB;
return parameters;
}
static void VolumetricLightingPass(in VolumetricLightingParameters parameters,
RTHandle depthTexture,
RTHandle densityBuffer,
RTHandle lightingBuffer,
RTHandle maxZTexture,
RTHandle historyRT,
RTHandle feedbackRT,
ComputeBuffer bigTileLightList,
CommandBuffer cmd)
{
if (parameters.tiledLighting)
cmd.SetComputeBufferParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs.g_vBigTileLightList, bigTileLightList);