-
Notifications
You must be signed in to change notification settings - Fork 868
Expand file tree
/
Copy pathLensFlareCommonSRP.cs
More file actions
1202 lines (1030 loc) · 57.2 KB
/
LensFlareCommonSRP.cs
File metadata and controls
1202 lines (1030 loc) · 57.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace UnityEngine.Rendering
{
/// <summary>
/// Common code for all Data-Driven Lens Flare used
/// </summary>
public sealed class LensFlareCommonSRP
{
private static LensFlareCommonSRP m_Instance = null;
private static readonly object m_Padlock = new object();
/// <summary>
/// Class describing internal information stored to describe a shown LensFlare
/// </summary>
internal class LensFlareCompInfo
{
/// <summary>
/// Index used to compute Occlusion in a fixed order
/// </summary>
internal int index;
/// <summary>
/// Component used
/// </summary>
internal LensFlareComponentSRP comp;
internal LensFlareCompInfo(int idx, LensFlareComponentSRP cmp)
{
index = idx;
comp = cmp;
}
}
private static System.Collections.Generic.List<LensFlareCompInfo> m_Data = new System.Collections.Generic.List<LensFlareCompInfo>();
private static System.Collections.Generic.List<int> m_AvailableIndicies = new System.Collections.Generic.List<int>();
/// <summary>
/// Max lens-flares-with-occlusion supported
/// </summary>
public static int maxLensFlareWithOcclusion = 128;
/// <summary>
/// With TAA Occlusion jitter depth, thought frame on HDRP.
/// So we do a "unanimity vote" for occlusion thought 'maxLensFlareWithOcclusionTemporalSample' frame
/// Important to keep this value maximum of 8
/// If this value change that could implies an implementation modification on:
/// com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareMergeOcclusionDataDriven.compute
/// </summary>
public static int maxLensFlareWithOcclusionTemporalSample = 8;
/// <summary>
/// Set to 1 to enable temporal sample merge.
/// Set to 0 to disable temporal sample merge (must support 16 bit textures, and the occlusion merge must be written in the last texel (vertical) of the lens flare texture.
/// </summary>
public static int mergeNeeded = 1;
/// <summary>
/// occlusion texture either provided or created automatically by the SRP for lens flare. (to be created automatically, please set mergeNeeded to 1).
/// Texture width is the max number of lens flares that have occlusion (x axis the lens flare index).
/// y axis is the number of samples (maxLensFlareWithOcclusionTemporalSample) plus the number of merge results.
/// Merge results must be done by the SRP and stored in the [(lens flareIndex), (maxLensFlareWithOcclusionTemporalSample + 1)] coordinate.
/// </summary>
public static RTHandle occlusionRT = null;
private static int frameIdx = 0;
private LensFlareCommonSRP()
{
}
/// <summary>
/// Initialization function which must be called by the SRP.
/// </summary>
static public void Initialize()
{
frameIdx = 0;
if (occlusionRT == null && mergeNeeded > 0)
occlusionRT = RTHandles.Alloc(width: maxLensFlareWithOcclusion, height: maxLensFlareWithOcclusionTemporalSample + 1 * mergeNeeded, colorFormat: Experimental.Rendering.GraphicsFormat.R16_SFloat, enableRandomWrite: true, dimension: TextureXR.dimension);
}
/// <summary>
/// Disposal function, must be called by the SRP to release all internal textures.
/// </summary>
static public void Dispose()
{
if (occlusionRT != null)
{
RTHandles.Release(occlusionRT);
occlusionRT = null;
}
}
/// <summary>
/// Current unique instance
/// </summary>
public static LensFlareCommonSRP Instance
{
get
{
if (m_Instance == null)
{
lock (m_Padlock)
{
if (m_Instance == null)
{
m_Instance = new LensFlareCommonSRP();
}
}
}
return m_Instance;
}
}
private System.Collections.Generic.List<LensFlareCompInfo> Data { get { return LensFlareCommonSRP.m_Data; } }
/// <summary>
/// Check if we have at least one Lens Flare added on the pool
/// </summary>
/// <returns>true if no Lens Flare were added</returns>
public bool IsEmpty()
{
return Data.Count == 0;
}
int GetNextAvailableIndex()
{
if (m_AvailableIndicies.Count == 0)
return m_Data.Count;
else
{
int nextIndex = m_AvailableIndicies[m_AvailableIndicies.Count - 1];
m_AvailableIndicies.RemoveAt(m_AvailableIndicies.Count - 1);
return nextIndex;
}
}
/// <summary>
/// Add a new lens flare component on the pool.
/// </summary>
/// <param name="newData">The new data added</param>
public void AddData(LensFlareComponentSRP newData)
{
Debug.Assert(Instance == this, "LensFlareCommonSRP can have only one instance");
if (!m_Data.Exists(x => x.comp == newData))
{
m_Data.Add(new LensFlareCompInfo(GetNextAvailableIndex(), newData));
}
}
/// <summary>
/// Remove a lens flare data which exist in the pool.
/// </summary>
/// <param name="data">The data which exist in the pool</param>
public void RemoveData(LensFlareComponentSRP data)
{
Debug.Assert(Instance == this, "LensFlareCommonSRP can have only one instance");
LensFlareCompInfo info = m_Data.Find(x => x.comp == data);
if (info != null)
{
int newIndex = info.index;
m_Data.Remove(info);
m_AvailableIndicies.Add(newIndex);
if (m_Data.Count == 0)
m_AvailableIndicies.Clear();
}
}
/// <summary>
/// Attenuation by Light Shape for Point Light
/// </summary>
/// <returns>Attenuation Factor</returns>
static public float ShapeAttenuationPointLight()
{
return 1.0f;
}
/// <summary>
/// Attenuation by Light Shape for Directional Light
/// </summary>
/// <param name="forward">Forward Vector of Directional Light</param>
/// <param name="wo">Vector pointing to the eye</param>
/// <returns>Attenuation Factor</returns>
static public float ShapeAttenuationDirLight(Vector3 forward, Vector3 wo)
{
return Mathf.Max(Vector3.Dot(forward, wo), 0.0f);
}
/// <summary>
/// Attenuation by Light Shape for Spot Light with Cone Shape
/// </summary>
/// <param name="forward">Forward Vector of Directional Light</param>
/// <param name="wo">Vector pointing to the eye</param>
/// <param name="spotAngle">The angle of the light's spotlight cone in degrees.</param>
/// <param name="innerSpotPercent01">Get the inner spot radius between 0 and 1.</param>
/// <returns>Attenuation Factor</returns>
static public float ShapeAttenuationSpotConeLight(Vector3 forward, Vector3 wo, float spotAngle, float innerSpotPercent01)
{
float outerDot = Mathf.Max(Mathf.Cos(0.5f * spotAngle * Mathf.Deg2Rad), 0.0f);
float innerDot = Mathf.Max(Mathf.Cos(0.5f * spotAngle * Mathf.Deg2Rad * innerSpotPercent01), 0.0f);
float dot = Mathf.Max(Vector3.Dot(forward, wo), 0.0f);
return Mathf.Clamp01((dot - outerDot) / (innerDot - outerDot));
}
/// <summary>
/// Attenuation by Light Shape for Spot Light with Box Shape
/// </summary>
/// <param name="forward">Forward Vector of Directional Light</param>
/// <param name="wo">Vector pointing to the eye</param>
/// <returns>Attenuation Factor</returns>
static public float ShapeAttenuationSpotBoxLight(Vector3 forward, Vector3 wo)
{
return Mathf.Max(Mathf.Sign(Vector3.Dot(forward, wo)), 0.0f);
}
/// <summary>
/// Attenuation by Light Shape for Spot Light with Pyramid Shape
/// </summary>
/// <param name="forward">Forward Vector of Directional Light</param>
/// <param name="wo">Vector pointing to the eye</param>
/// <returns>Attenuation Factor</returns>
static public float ShapeAttenuationSpotPyramidLight(Vector3 forward, Vector3 wo)
{
return ShapeAttenuationSpotBoxLight(forward, wo);
}
/// <summary>
/// Attenuation by Light Shape for Area Light with Tube Shape
/// </summary>
/// <param name="lightPositionWS">World Space position of the Light</param>
/// <param name="lightSide">Vector pointing to the side (right or left) or the light</param>
/// <param name="lightWidth">Width (half extent) of the tube light</param>
/// <param name="cam">Camera rendering the Tube Light</param>
/// <returns>Attenuation Factor</returns>
static public float ShapeAttenuationAreaTubeLight(Vector3 lightPositionWS, Vector3 lightSide, float lightWidth, Camera cam)
{
// Ref: https://hal.archives-ouvertes.fr/hal-02155101/document
// Listing 1.6. Analytic line-diffuse integration.
float Fpo(float d, float l)
{
return l / (d * (d * d + l * l)) + Mathf.Atan(l / d) / (d * d);
}
float Fwt(float d, float l)
{
return l * l / (d * (d * d + l * l));
}
Vector3 p1Global = lightPositionWS + 0.5f * lightWidth * lightSide;
Vector3 p2Global = lightPositionWS - 0.5f * lightWidth * lightSide;
Vector3 p1Front = lightPositionWS + 0.5f * lightWidth * cam.transform.right;
Vector3 p2Front = lightPositionWS - 0.5f * lightWidth * cam.transform.right;
Vector3 p1World = cam.transform.InverseTransformPoint(p1Global);
Vector3 p2World = cam.transform.InverseTransformPoint(p2Global);
Vector3 p1WorldFront = cam.transform.InverseTransformPoint(p1Front);
Vector3 p2WorldFront = cam.transform.InverseTransformPoint(p2Front);
float DiffLineIntegral(Vector3 p1, Vector3 p2)
{
float diffIntegral;
// tangent
Vector3 wt = (p2 - p1).normalized;
// clamping
if (p1.z <= 0.0 && p2.z <= 0.0)
{
diffIntegral = 0.0f;
}
else
{
if (p1.z < 0.0)
p1 = (p1 * p2.z - p2 * p1.z) / (+p2.z - p1.z);
if (p2.z < 0.0)
p2 = (-p1 * p2.z + p2 * p1.z) / (-p2.z + p1.z);
// parameterization
float l1 = Vector3.Dot(p1, wt);
float l2 = Vector3.Dot(p2, wt);
// shading point orthonormal projection on the line
Vector3 po = p1 - l1 * wt;
// distance to line
float d = po.magnitude;
// integral
float integral = (Fpo(d, l2) - Fpo(d, l1)) * po.z + (Fwt(d, l2) - Fwt(d, l1)) * wt.z;
diffIntegral = integral / Mathf.PI;
}
return diffIntegral;
}
float frontModulation = DiffLineIntegral(p1WorldFront, p2WorldFront);
float worldModulation = DiffLineIntegral(p1World, p2World);
return frontModulation > 0.0f ? worldModulation / frontModulation : 1.0f;
}
/// <summary>
/// Attenuation by Light Shape for Area Light with Rectangular Shape
/// </summary>
/// <param name="forward">Forward Vector of Directional Light</param>
/// <param name="wo">Vector pointing to the eye</param>
/// <returns>Attenuation Factor</returns>
static public float ShapeAttenuationAreaRectangleLight(Vector3 forward, Vector3 wo)
{
return ShapeAttenuationDirLight(forward, wo);
}
/// <summary>
/// Attenuation by Light Shape for Area Light with Disc Shape
/// </summary>
/// <param name="forward">Forward Vector of Directional Light</param>
/// <param name="wo">Vector pointing to the eye</param>
/// <returns>Attenuation Factor</returns>
static public float ShapeAttenuationAreaDiscLight(Vector3 forward, Vector3 wo)
{
return ShapeAttenuationDirLight(forward, wo);
}
/// <summary>
/// Compute internal parameters needed to render single flare
/// </summary>
/// <param name="screenPos"></param>
/// <param name="translationScale"></param>
/// <param name="rayOff0"></param>
/// <param name="vLocalScreenRatio"></param>
/// <param name="angleDeg"></param>
/// <param name="position"></param>
/// <param name="angularOffset"></param>
/// <param name="positionOffset"></param>
/// <param name="autoRotate"></param>
/// <returns>Parameter used on the shader for _FlareData0</returns>
static public Vector4 GetFlareData0(Vector2 screenPos, Vector2 translationScale, Vector2 rayOff0, Vector2 vLocalScreenRatio, float angleDeg, float position, float angularOffset, Vector2 positionOffset, bool autoRotate)
{
if (!SystemInfo.graphicsUVStartsAtTop)
{
angleDeg *= -1;
positionOffset.y *= -1;
}
float globalCos0 = Mathf.Cos(-angularOffset * Mathf.Deg2Rad);
float globalSin0 = Mathf.Sin(-angularOffset * Mathf.Deg2Rad);
Vector2 rayOff = -translationScale * (screenPos + screenPos * (position - 1.0f));
rayOff = new Vector2(globalCos0 * rayOff.x - globalSin0 * rayOff.y,
globalSin0 * rayOff.x + globalCos0 * rayOff.y);
float rotation = angleDeg;
rotation += 180.0f;
//if (!autoRotate)
//{
// //rotation = Mathf.Abs(rotation) < 1e-4f ? 360.0f : rotation;
//}
//else
if (autoRotate)
{
Vector2 pos = (rayOff.normalized * vLocalScreenRatio) * translationScale;
rotation += -Mathf.Rad2Deg * Mathf.Atan2(pos.y, pos.x);
}
rotation *= Mathf.Deg2Rad;
float localCos0 = Mathf.Cos(-rotation);
float localSin0 = Mathf.Sin(-rotation);
return new Vector4(localCos0, localSin0, positionOffset.x + rayOff0.x * translationScale.x, -positionOffset.y + rayOff0.y * translationScale.y);
}
static Vector2 GetLensFlareRayOffset(Vector2 screenPos, float position, float globalCos0, float globalSin0)
{
Vector2 rayOff = -(screenPos + screenPos * (position - 1.0f));
return new Vector2(globalCos0 * rayOff.x - globalSin0 * rayOff.y,
globalSin0 * rayOff.x + globalCos0 * rayOff.y);
}
static Vector3 WorldToViewport(Camera camera, bool isLocalLight, bool isCameraRelative, Matrix4x4 viewProjMatrix, Vector3 positionWS)
{
if (isLocalLight)
{
return WorldToViewportLocal(isCameraRelative, viewProjMatrix, camera.transform.position, positionWS);
}
else
{
return WorldToViewportDistance(camera, positionWS);
}
}
static Vector3 WorldToViewportLocal(bool isCameraRelative, Matrix4x4 viewProjMatrix, Vector3 cameraPosWS, Vector3 positionWS)
{
Vector3 localPositionWS = positionWS;
if (isCameraRelative)
{
localPositionWS -= cameraPosWS;
}
Vector4 viewportPos4 = viewProjMatrix * localPositionWS;
Vector3 viewportPos = new Vector3(viewportPos4.x, viewportPos4.y, 0f);
viewportPos /= viewportPos4.w;
viewportPos.x = viewportPos.x * 0.5f + 0.5f;
viewportPos.y = viewportPos.y * 0.5f + 0.5f;
viewportPos.y = 1.0f - viewportPos.y;
viewportPos.z = viewportPos4.w;
return viewportPos;
}
static Vector3 WorldToViewportDistance(Camera cam, Vector3 positionWS)
{
Vector4 camPos = cam.worldToCameraMatrix * positionWS;
Vector4 viewportPos4 = cam.projectionMatrix * camPos;
Vector3 viewportPos = new Vector3(viewportPos4.x, viewportPos4.y, 0f);
viewportPos /= viewportPos4.w;
viewportPos.x = viewportPos.x * 0.5f + 0.5f;
viewportPos.y = viewportPos.y * 0.5f + 0.5f;
viewportPos.z = viewportPos4.w;
return viewportPos;
}
/// <summary>
/// Effective Job of drawing the set of Lens Flare registered
/// </summary>
/// <param name="lensFlareShader">Lens Flare material (HDRP or URP shader)</param>
/// <param name="lensFlares">Set of Lens Flare</param>
/// <param name="cam">Camera</param>
/// <param name="actualWidth">Width actually used for rendering after dynamic resolution and XR is applied.</param>
/// <param name="actualHeight">Height actually used for rendering after dynamic resolution and XR is applied.</param>
/// <param name="usePanini">Set if use Panani Projection</param>
/// <param name="paniniDistance">Distance used for Panini projection</param>
/// <param name="paniniCropToFit">CropToFit parameter used for Panini projection</param>
/// <param name="isCameraRelative">Set if camera is relative</param>
/// <param name="cameraPositionWS">Camera World Space position</param>
/// <param name="viewProjMatrix">View Projection Matrix of the current camera</param>
/// <param name="cmd">Command Buffer</param>
/// <param name="taaEnabled">Set if TAA is enabled</param>
/// <param name="sunOcclusionTexture">Sun Occlusion Texture from VolumetricCloud on HDRP or null</param>
/// <param name="_FlareOcclusionTex">ShaderID for the FlareOcclusionTex</param>
/// <param name="_FlareOcclusionIndex">ShaderID for the FlareOcclusionIndex</param>
/// <param name="_FlareTex">ShaderID for the FlareTex</param>
/// <param name="_FlareColorValue">ShaderID for the FlareColor</param>
/// <param name="_FlareSunOcclusionTex">ShaderID for the _FlareSunOcclusionTex</param>
/// <param name="_FlareData0">ShaderID for the FlareData0</param>
/// <param name="_FlareData1">ShaderID for the FlareData1</param>
/// <param name="_FlareData2">ShaderID for the FlareData2</param>
/// <param name="_FlareData3">ShaderID for the FlareData3</param>
/// <param name="_FlareData4">ShaderID for the FlareData4</param>
static public void ComputeOcclusion(Material lensFlareShader, LensFlareCommonSRP lensFlares, Camera cam,
float actualWidth, float actualHeight,
bool usePanini, float paniniDistance, float paniniCropToFit, bool isCameraRelative,
Vector3 cameraPositionWS,
Matrix4x4 viewProjMatrix,
Rendering.CommandBuffer cmd,
Texture sunOcclusionTexture,
bool taaEnabled,
int _FlareSunOcclusionTex, int _FlareOcclusionTex, int _FlareOcclusionIndex, int _FlareTex, int _FlareColorValue, int _FlareData0, int _FlareData1, int _FlareData2, int _FlareData3, int _FlareData4)
{
Vector2 vScreenRatio;
if (lensFlares.IsEmpty() || occlusionRT == null)
return;
Vector2 screenSize = new Vector2(actualWidth, actualHeight);
float screenRatio = screenSize.x / screenSize.y;
vScreenRatio = new Vector2(screenRatio, 1.0f);
#if UNITY_EDITOR
if (cam.cameraType == CameraType.SceneView)
{
// Determine whether the "Animated Materials" checkbox is checked for the current view.
for (int i = 0; i < UnityEditor.SceneView.sceneViews.Count; i++) // Using a foreach on an ArrayList generates garbage ...
{
var sv = UnityEditor.SceneView.sceneViews[i] as UnityEditor.SceneView;
if (sv.camera == cam && !sv.sceneViewState.flaresEnabled)
{
return;
}
}
}
#endif
Rendering.CoreUtils.SetRenderTarget(cmd, occlusionRT);
if (!taaEnabled)
{
cmd.ClearRenderTarget(false, true, Color.black);
}
float dx = 1.0f / ((float)maxLensFlareWithOcclusion);
float dy = 1.0f / ((float)(maxLensFlareWithOcclusionTemporalSample + mergeNeeded));
float halfx = 0.5f / ((float)maxLensFlareWithOcclusion);
float halfy = 0.5f / ((float)(maxLensFlareWithOcclusionTemporalSample + mergeNeeded));
int taaValue = taaEnabled ? 1 : 0;
foreach (LensFlareCompInfo info in m_Data)
{
if (info == null || info.comp == null)
continue;
LensFlareComponentSRP comp = info.comp;
LensFlareDataSRP data = comp.lensFlareData;
if (!comp.enabled ||
!comp.gameObject.activeSelf ||
!comp.gameObject.activeInHierarchy ||
data == null ||
data.elements == null ||
data.elements.Length == 0 ||
comp.intensity <= 0.0f ||
!comp.useOcclusion ||
(comp.useOcclusion && comp.sampleCount == 0))
continue;
Light light = comp.GetComponent<Light>();
Vector3 positionWS;
Vector3 viewportPos;
bool isDirLight = false;
if (light != null && light.type == LightType.Directional)
{
positionWS = -light.transform.forward * cam.farClipPlane;
isDirLight = true;
}
else
{
positionWS = comp.transform.position;
}
viewportPos = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS);
if (usePanini && cam == Camera.main)
{
viewportPos = DoPaniniProjection(viewportPos, actualWidth, actualHeight, cam.fieldOfView, paniniCropToFit, paniniDistance);
}
if (viewportPos.z < 0.0f)
continue;
if (!comp.allowOffScreen)
{
if (viewportPos.x < 0.0f || viewportPos.x > 1.0f ||
viewportPos.y < 0.0f || viewportPos.y > 1.0f)
continue;
}
Vector3 diffToObject = positionWS - cameraPositionWS;
// Check if the light is forward, can be an issue with,
// the math associated to Panini projection
if (Vector3.Dot(cam.transform.forward, diffToObject) < 0.0f)
{
continue;
}
float distToObject = diffToObject.magnitude;
float coefDistSample = distToObject / comp.maxAttenuationDistance;
float coefScaleSample = distToObject / comp.maxAttenuationScale;
float distanceAttenuation = !isDirLight && comp.distanceAttenuationCurve.length > 0 ? comp.distanceAttenuationCurve.Evaluate(coefDistSample) : 1.0f;
float scaleByDistance = !isDirLight && comp.scaleByDistanceCurve.length >= 1 ? comp.scaleByDistanceCurve.Evaluate(coefScaleSample) : 1.0f;
Vector3 dir = (cam.transform.position - comp.transform.position).normalized;
Vector3 screenPosZ = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS + dir * comp.occlusionOffset);
float adjustedOcclusionRadius = isDirLight ? comp.celestialProjectedOcclusionRadius(cam) : comp.occlusionRadius;
Vector2 occlusionRadiusEdgeScreenPos0 = (Vector2)viewportPos;
Vector2 occlusionRadiusEdgeScreenPos1 = (Vector2)WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS + cam.transform.up * adjustedOcclusionRadius);
float occlusionRadius = (occlusionRadiusEdgeScreenPos1 - occlusionRadiusEdgeScreenPos0).magnitude;
cmd.SetGlobalVector(_FlareData1, new Vector4(occlusionRadius, comp.sampleCount, screenPosZ.z, actualHeight / actualWidth));
cmd.EnableShaderKeyword("FLARE_COMPUTE_OCCLUSION");
if (sunOcclusionTexture != null)
{
if (comp.volumetricCloudOcclusion)
{
cmd.EnableShaderKeyword("FLARE_SAMPLE_WITH_VOLUMETRIC_CLOUD");
cmd.SetGlobalTexture(_FlareSunOcclusionTex, sunOcclusionTexture);
}
else
{
cmd.DisableShaderKeyword("FLARE_SAMPLE_WITH_VOLUMETRIC_CLOUD");
}
}
else
{
cmd.DisableShaderKeyword("FLARE_SAMPLE_WITH_VOLUMETRIC_CLOUD");
}
Vector2 screenPos = new Vector2(2.0f * viewportPos.x - 1.0f, 1.0f - 2.0f * viewportPos.y);
Vector2 radPos = new Vector2(Mathf.Abs(screenPos.x), Mathf.Abs(screenPos.y));
float radius = Mathf.Max(radPos.x, radPos.y); // l1 norm (instead of l2 norm)
float radialsScaleRadius = comp.radialScreenAttenuationCurve.length > 0 ? comp.radialScreenAttenuationCurve.Evaluate(radius) : 1.0f;
float compIntensity = comp.intensity * radialsScaleRadius * distanceAttenuation;
if (compIntensity <= 0.0f)
continue;
float globalCos0 = Mathf.Cos(0.0f);
float globalSin0 = Mathf.Sin(0.0f);
float position = 0.0f;
float usedGradientPosition = Mathf.Clamp01(1.0f - 1e-6f);
cmd.SetGlobalVector(_FlareData3, new Vector4(comp.allowOffScreen ? 1.0f : -1.0f, usedGradientPosition, Mathf.Exp(Mathf.Lerp(0.0f, 4.0f, 1.0f)), 1.0f / 3.0f));
Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0);
Vector4 flareData0 = GetFlareData0(screenPos, Vector2.one, rayOff, vScreenRatio, 0.0f, position, 0.0f, Vector2.zero, false);
cmd.SetGlobalVector(_FlareData0, flareData0);
cmd.SetGlobalVector(_FlareData2, new Vector4(screenPos.x, screenPos.y, 0.0f, 0.0f));
Rect rect = new Rect() { x = info.index, y = (frameIdx + mergeNeeded) * taaValue, width = 1, height = 1 };
cmd.SetViewport(rect);
UnityEngine.Rendering.Blitter.DrawQuad(cmd, lensFlareShader, 4);
}
// Clear the remaining buffer
{
cmd.SetRenderTarget(occlusionRT);
cmd.SetViewport(new Rect() { x = m_Data.Count, y = 0, width = (maxLensFlareWithOcclusion - m_Data.Count), height = (maxLensFlareWithOcclusionTemporalSample + mergeNeeded) });
cmd.ClearRenderTarget(false, true, Color.black);
}
++frameIdx;
frameIdx %= maxLensFlareWithOcclusionTemporalSample;
}
/// <summary>
/// Effective Job of drawing the set of Lens Flare registered
/// </summary>
/// <param name="lensFlareShader">Lens Flare material (HDRP or URP shader)</param>
/// <param name="lensFlares">Set of Lens Flare</param>
/// <param name="cam">Camera</param>
/// <param name="actualWidth">Width actually used for rendering after dynamic resolution and XR is applied.</param>
/// <param name="actualHeight">Height actually used for rendering after dynamic resolution and XR is applied.</param>
/// <param name="usePanini">Set if use Panani Projection</param>
/// <param name="paniniDistance">Distance used for Panini projection</param>
/// <param name="paniniCropToFit">CropToFit parameter used for Panini projection</param>
/// <param name="isCameraRelative">Set if camera is relative</param>
/// <param name="cameraPositionWS">Camera World Space position</param>
/// <param name="viewProjMatrix">View Projection Matrix of the current camera</param>
/// <param name="cmd">Command Buffer</param>
/// <param name="colorBuffer">Source Render Target which contains the Color Buffer</param>
/// <param name="GetLensFlareLightAttenuation">Delegate to which return return the Attenuation of the light based on their shape which uses the functions ShapeAttenuation...(...), must reimplemented per SRP</param>
/// <param name="_FlareOcclusionTex">ShaderID for the FlareOcclusionTex</param>
/// <param name="_FlareOcclusionIndex">ShaderID for the FlareOcclusionIndex</param>
/// <param name="_FlareOcclusionRemapTex">ShaderID for the OcclusionRemap</param>
/// <param name="_FlareTex">ShaderID for the FlareTex</param>
/// <param name="_FlareColorValue">ShaderID for the FlareColor</param>
/// <param name="_FlareData0">ShaderID for the FlareData0</param>
/// <param name="_FlareData1">ShaderID for the FlareData1</param>
/// <param name="_FlareData2">ShaderID for the FlareData2</param>
/// <param name="_FlareData3">ShaderID for the FlareData3</param>
/// <param name="_FlareData4">ShaderID for the FlareData4</param>
/// <param name="taaEnabled">Set if TAA is enabled</param>
/// <param name="debugView">Debug View which setup black background to see only Lens Flare</param>
static public void DoLensFlareDataDrivenCommon(Material lensFlareShader, LensFlareCommonSRP lensFlares, Camera cam, float actualWidth, float actualHeight,
bool usePanini, float paniniDistance, float paniniCropToFit,
bool isCameraRelative,
Vector3 cameraPositionWS,
Matrix4x4 viewProjMatrix,
Rendering.CommandBuffer cmd,
Rendering.RenderTargetIdentifier colorBuffer,
System.Func<Light, Camera, Vector3, float> GetLensFlareLightAttenuation,
int _FlareOcclusionRemapTex, int _FlareOcclusionTex, int _FlareOcclusionIndex, int _FlareTex, int _FlareColorValue, int _FlareData0, int _FlareData1, int _FlareData2, int _FlareData3, int _FlareData4,
bool taaEnabled, bool debugView)
{
Vector2 vScreenRatio;
if (lensFlares.IsEmpty() || occlusionRT == null)
return;
Vector2 screenSize = new Vector2(actualWidth, actualHeight);
float screenRatio = screenSize.x / screenSize.y;
vScreenRatio = new Vector2(screenRatio, 1.0f);
Rendering.CoreUtils.SetRenderTarget(cmd, colorBuffer);
cmd.SetViewport(new Rect() { width = screenSize.x, height = screenSize.y });
if (debugView)
{
// Background pitch black to see only the Flares
cmd.ClearRenderTarget(false, true, Color.black);
}
#if UNITY_EDITOR
if (cam.cameraType == CameraType.SceneView)
{
// Determine whether the "Animated Materials" checkbox is checked for the current view.
for (int i = 0; i < UnityEditor.SceneView.sceneViews.Count; i++) // Using a foreach on an ArrayList generates garbage ...
{
var sv = UnityEditor.SceneView.sceneViews[i] as UnityEditor.SceneView;
if (sv.camera == cam && !sv.sceneViewState.flaresEnabled)
{
return;
}
}
}
#endif
foreach (LensFlareCompInfo info in m_Data)
{
if (info == null || info.comp == null)
continue;
LensFlareComponentSRP comp = info.comp;
LensFlareDataSRP data = comp.lensFlareData;
if (!comp.enabled ||
!comp.gameObject.activeSelf ||
!comp.gameObject.activeInHierarchy ||
data == null ||
data.elements == null ||
data.elements.Length == 0 ||
comp.intensity <= 0.0f)
continue;
Light light = comp.GetComponent<Light>();
Vector3 positionWS;
Vector3 viewportPos;
bool isDirLight = false;
if (light != null && light.type == LightType.Directional)
{
positionWS = -light.transform.forward * cam.farClipPlane;
isDirLight = true;
}
else
{
positionWS = comp.transform.position;
}
viewportPos = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS);
if (usePanini && cam == Camera.main)
{
viewportPos = DoPaniniProjection(viewportPos, actualWidth, actualHeight, cam.fieldOfView, paniniCropToFit, paniniDistance);
}
if (viewportPos.z < 0.0f)
continue;
if (!comp.allowOffScreen)
{
if (viewportPos.x < 0.0f || viewportPos.x > 1.0f ||
viewportPos.y < 0.0f || viewportPos.y > 1.0f)
continue;
}
Vector3 diffToObject = positionWS - cameraPositionWS;
// Check if the light is forward, can be an issue with,
// the math associated to Panini projection
if (Vector3.Dot(cam.transform.forward, diffToObject) < 0.0f)
{
continue;
}
float distToObject = diffToObject.magnitude;
float coefDistSample = distToObject / comp.maxAttenuationDistance;
float coefScaleSample = distToObject / comp.maxAttenuationScale;
float distanceAttenuation = !isDirLight && comp.distanceAttenuationCurve.length > 0 ? comp.distanceAttenuationCurve.Evaluate(coefDistSample) : 1.0f;
float scaleByDistance = !isDirLight && comp.scaleByDistanceCurve.length >= 1 ? comp.scaleByDistanceCurve.Evaluate(coefScaleSample) : 1.0f;
Color globalColorModulation = Color.white;
if (light != null)
{
if (comp.attenuationByLightShape)
globalColorModulation *= GetLensFlareLightAttenuation(light, cam, -diffToObject.normalized);
}
Vector2 screenPos = new Vector2(2.0f * viewportPos.x - 1.0f, 1.0f - 2.0f * viewportPos.y);
Vector2 radPos = new Vector2(Mathf.Abs(screenPos.x), Mathf.Abs(screenPos.y));
float radius = Mathf.Max(radPos.x, radPos.y); // l1 norm (instead of l2 norm)
float radialsScaleRadius = comp.radialScreenAttenuationCurve.length > 0 ? comp.radialScreenAttenuationCurve.Evaluate(radius) : 1.0f;
float compIntensity = comp.intensity * radialsScaleRadius * distanceAttenuation;
if (compIntensity <= 0.0f)
continue;
globalColorModulation *= distanceAttenuation;
Vector3 dir = (cam.transform.position - comp.transform.position).normalized;
Vector3 screenPosZ = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS + dir * comp.occlusionOffset);
float adjustedOcclusionRadius = isDirLight ? comp.celestialProjectedOcclusionRadius(cam) : comp.occlusionRadius;
Vector2 occlusionRadiusEdgeScreenPos0 = (Vector2)viewportPos;
Vector2 occlusionRadiusEdgeScreenPos1 = (Vector2)WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS + cam.transform.up * adjustedOcclusionRadius);
float occlusionRadius = (occlusionRadiusEdgeScreenPos1 - occlusionRadiusEdgeScreenPos0).magnitude;
cmd.SetGlobalVector(_FlareData1, new Vector4(occlusionRadius, comp.sampleCount, screenPosZ.z, actualHeight / actualWidth));
if (comp.useOcclusion && taaEnabled)
{
cmd.EnableShaderKeyword("FLARE_OCCLUSION");
cmd.DisableShaderKeyword("FLARE_MEASURE_OCCLUSION");
}
else if (comp.useOcclusion && !taaEnabled)
{
cmd.DisableShaderKeyword("FLARE_OCCLUSION");
cmd.EnableShaderKeyword("FLARE_MEASURE_OCCLUSION");
}
else
{
cmd.DisableShaderKeyword("FLARE_OCCLUSION");
cmd.DisableShaderKeyword("FLARE_MEASURE_OCCLUSION");
}
if (taaEnabled && occlusionRT != null)
cmd.SetGlobalTexture(_FlareOcclusionTex, occlusionRT);
cmd.SetGlobalVector(_FlareOcclusionIndex, new Vector4((float)info.index, 0.0f, 0.0f, 0.0f));
cmd.SetGlobalTexture(_FlareOcclusionRemapTex, comp.occlusionRemapCurve.GetTexture());
foreach (LensFlareDataElementSRP element in data.elements)
{
if (element == null ||
element.visible == false ||
(element.lensFlareTexture == null && element.flareType == SRPLensFlareType.Image) ||
element.localIntensity <= 0.0f ||
element.count <= 0 ||
element.localIntensity <= 0.0f)
continue;
Color colorModulation = globalColorModulation;
if (light != null && element.modulateByLightColor)
{
if (light.useColorTemperature)
colorModulation *= light.color * Mathf.CorrelatedColorTemperatureToRGB(light.colorTemperature);
else
colorModulation *= light.color;
}
Color curColor = colorModulation;
float currentIntensity = element.localIntensity * compIntensity;
if (currentIntensity <= 0.0f)
continue;
Texture texture = element.lensFlareTexture;
float usedAspectRatio;
if (element.flareType == SRPLensFlareType.Image)
usedAspectRatio = element.preserveAspectRatio ? ((((float)texture.height) / (float)texture.width)) : 1.0f;
else
usedAspectRatio = 1.0f;
float rotation = element.rotation;
Vector2 elemSizeXY;
if (element.preserveAspectRatio)
{
if (usedAspectRatio >= 1.0f)
{
elemSizeXY = new Vector2(element.sizeXY.x / usedAspectRatio, element.sizeXY.y);
}
else
{
elemSizeXY = new Vector2(element.sizeXY.x, element.sizeXY.y * usedAspectRatio);
}
}
else
{
elemSizeXY = new Vector2(element.sizeXY.x, element.sizeXY.y);
}
float scaleSize = 0.1f; // Arbitrary value
Vector2 size = new Vector2(elemSizeXY.x, elemSizeXY.y);
float combinedScale = scaleByDistance * scaleSize * element.uniformScale * comp.scale;
size *= combinedScale;
curColor *= element.tint;
curColor *= currentIntensity;
float angularOffset = SystemInfo.graphicsUVStartsAtTop ? element.angularOffset : -element.angularOffset;
float globalCos0 = Mathf.Cos(-angularOffset * Mathf.Deg2Rad);
float globalSin0 = Mathf.Sin(-angularOffset * Mathf.Deg2Rad);
float position = 2.0f * element.position;
SRPLensFlareBlendMode blendMode = element.blendMode;
int materialPass;
if (blendMode == SRPLensFlareBlendMode.Additive)
materialPass = 0;
else if (blendMode == SRPLensFlareBlendMode.Screen)
materialPass = 1;
else if (blendMode == SRPLensFlareBlendMode.Premultiply)
materialPass = 2;
else if (blendMode == SRPLensFlareBlendMode.Lerp)
materialPass = 3;
else
materialPass = 0;
if (element.flareType == SRPLensFlareType.Image)
{
cmd.DisableShaderKeyword("FLARE_CIRCLE");
cmd.DisableShaderKeyword("FLARE_POLYGON");
}
else if (element.flareType == SRPLensFlareType.Circle)
{
cmd.EnableShaderKeyword("FLARE_CIRCLE");
cmd.DisableShaderKeyword("FLARE_POLYGON");
}
else if (element.flareType == SRPLensFlareType.Polygon)
{
cmd.DisableShaderKeyword("FLARE_CIRCLE");
cmd.EnableShaderKeyword("FLARE_POLYGON");
}
if (element.flareType == SRPLensFlareType.Circle ||
element.flareType == SRPLensFlareType.Polygon)
{
if (element.inverseSDF)
{
cmd.EnableShaderKeyword("FLARE_INVERSE_SDF");
}
else
{
cmd.DisableShaderKeyword("FLARE_INVERSE_SDF");
}
}
else
{
cmd.DisableShaderKeyword("FLARE_INVERSE_SDF");
}
if (element.lensFlareTexture != null)
cmd.SetGlobalTexture(_FlareTex, element.lensFlareTexture);
float usedGradientPosition = Mathf.Clamp01((1.0f - element.edgeOffset) - 1e-6f);
if (element.flareType == SRPLensFlareType.Polygon)
usedGradientPosition = Mathf.Pow(usedGradientPosition + 1.0f, 5);
Vector2 ComputeLocalSize(Vector2 rayOff, Vector2 rayOff0, Vector2 curSize, AnimationCurve distortionCurve)
{
Vector2 rayOffZ = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0);
Vector2 localRadPos;
float localRadius;
if (!element.distortionRelativeToCenter)
{
localRadPos = (rayOff - rayOff0) * 0.5f;
localRadius = Mathf.Clamp01(Mathf.Max(Mathf.Abs(localRadPos.x), Mathf.Abs(localRadPos.y))); // l1 norm (instead of l2 norm)
}
else
{
localRadPos = screenPos + (rayOff + new Vector2(element.positionOffset.x, -element.positionOffset.y)) * element.translationScale;
localRadius = Mathf.Clamp01(localRadPos.magnitude); // l2 norm (instead of l1 norm)
}
float localLerpValue = Mathf.Clamp01(distortionCurve.Evaluate(localRadius));
return new Vector2(Mathf.Lerp(curSize.x, element.targetSizeDistortion.x * combinedScale / usedAspectRatio, localLerpValue),
Mathf.Lerp(curSize.y, element.targetSizeDistortion.y * combinedScale, localLerpValue));
}
float usedSDFRoundness = element.sdfRoundness;
cmd.SetGlobalVector(_FlareData3, new Vector4(comp.allowOffScreen ? 1.0f : -1.0f, usedGradientPosition, Mathf.Exp(Mathf.Lerp(0.0f, 4.0f, Mathf.Clamp01(1.0f - element.fallOff))), 1.0f / (float)element.sideCount));
if (element.flareType == SRPLensFlareType.Polygon)
{
float invSide = 1.0f / (float)element.sideCount;
float rCos = Mathf.Cos(Mathf.PI * invSide);
float roundValue = rCos * usedSDFRoundness;
float r = rCos - roundValue;
float an = 2.0f * Mathf.PI * invSide;
float he = r * Mathf.Tan(0.5f * an);
cmd.SetGlobalVector(_FlareData4, new Vector4(usedSDFRoundness, r, an, he));
}
else
{
cmd.SetGlobalVector(_FlareData4, new Vector4(usedSDFRoundness, 0.0f, 0.0f, 0.0f));
}
if (!element.allowMultipleElement || element.count == 1)
{
Vector2 localSize = size;
Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0);
if (element.enableRadialDistortion)
{
Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0);
localSize = ComputeLocalSize(rayOff, rayOff0, localSize, element.distortionCurve);
}
Vector4 flareData0 = GetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, rotation, position, angularOffset, element.positionOffset, element.autoRotate);
cmd.SetGlobalVector(_FlareData0, flareData0);
cmd.SetGlobalVector(_FlareData2, new Vector4(screenPos.x, screenPos.y, localSize.x, localSize.y));
cmd.SetGlobalVector(_FlareColorValue, curColor);
UnityEngine.Rendering.Blitter.DrawQuad(cmd, lensFlareShader, materialPass);
}
else
{
float dLength = 2.0f * element.lengthSpread / ((float)(element.count - 1));
if (element.distribution == SRPLensFlareDistribution.Uniform)
{
float uniformAngle = 0.0f;
for (int elemIdx = 0; elemIdx < element.count; ++elemIdx)
{
Vector2 localSize = size;
Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0);
if (element.enableRadialDistortion)
{
Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0);
localSize = ComputeLocalSize(rayOff, rayOff0, localSize, element.distortionCurve);
}