-
Notifications
You must be signed in to change notification settings - Fork 868
Expand file tree
/
Copy pathPostProcessLayer.cs
More file actions
1440 lines (1215 loc) · 62.3 KB
/
PostProcessLayer.cs
File metadata and controls
1440 lines (1215 loc) · 62.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.Collections.Generic;
using System.Linq;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering.PostProcessing
{
#if (ENABLE_VR_MODULE && ENABLE_VR)
using XRSettings = UnityEngine.XR.XRSettings;
#endif
/// <summary>
/// This is the component responsible for rendering post-processing effects. It must be put on
/// every camera you want post-processing to be applied to.
/// </summary>
#if UNITY_2018_3_OR_NEWER
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[DisallowMultipleComponent, ImageEffectAllowedInSceneView]
[AddComponentMenu("Rendering/Post-process Layer", 1000)]
[RequireComponent(typeof(Camera))]
public sealed class PostProcessLayer : MonoBehaviour
{
/// <summary>
/// Builtin anti-aliasing methods.
/// </summary>
public enum Antialiasing
{
/// <summary>
/// No anti-aliasing.
/// </summary>
None,
/// <summary>
/// Fast Approximate Anti-aliasing (FXAA). Fast but low quality.
/// </summary>
FastApproximateAntialiasing,
/// <summary>
/// Subpixel Morphological Anti-aliasing (SMAA). Slower but higher quality than FXAA.
/// </summary>
SubpixelMorphologicalAntialiasing,
/// <summary>
/// Temporal Anti-aliasing (TAA). As fast as SMAA but generally higher quality. Because
/// of it's temporal nature, it can introduce ghosting artifacts on fast moving objects
/// in highly contrasted areas.
/// </summary>
TemporalAntialiasing
}
/// <summary>
/// This is transform that will be drive the volume blending feature. In some cases you may
/// want to use a transform other than the camera, e.g. for a top down game you'll want the
/// player character to drive the blending instead of the actual camera transform.
/// Setting this field to <c>null</c> will disable local volumes for this layer (global ones
/// will still work).
/// </summary>
public Transform volumeTrigger;
/// <summary>
/// A mask of layers to consider for volume blending. It allows you to do volume filtering
/// and is especially useful to optimize volume traversal. You should always have your
/// volumes in dedicated layers instead of the default one for best performances.
/// </summary>
public LayerMask volumeLayer;
/// <summary>
/// If <c>true</c>, it will kill any invalid / NaN pixel and replace it with a black color
/// before post-processing is applied. It's generally a good idea to keep this enabled to
/// avoid post-processing artifacts cause by broken data in the scene.
/// </summary>
public bool stopNaNPropagation = true;
/// <summary>
/// If <c>true</c>, it will render straight to the backbuffer and save the final blit done
/// by the engine. This has less overhead and will improve performance on lower-end platforms
/// (like mobiles) but breaks compatibility with legacy image effect that use OnRenderImage.
/// </summary>
public bool finalBlitToCameraTarget = false;
/// <summary>
/// The anti-aliasing method to use for this camera. By default it's set to <c>None</c>.
/// </summary>
public Antialiasing antialiasingMode = Antialiasing.None;
/// <summary>
/// Temporal Anti-aliasing settings for this camera.
/// </summary>
public TemporalAntialiasing temporalAntialiasing;
/// <summary>
/// Subpixel Morphological Anti-aliasing settings for this camera.
/// </summary>
public SubpixelMorphologicalAntialiasing subpixelMorphologicalAntialiasing;
/// <summary>
/// Fast Approximate Anti-aliasing settings for this camera.
/// </summary>
public FastApproximateAntialiasing fastApproximateAntialiasing;
/// <summary>
/// Fog settings for this camera.
/// </summary>
public Fog fog;
Dithering dithering;
/// <summary>
/// The debug layer is reponsible for rendering debugging information on the screen. It will
/// only be used if this layer is referenced in a <see cref="PostProcessDebug"/> component.
/// </summary>
/// <seealso cref="PostProcessDebug"/>
public PostProcessDebugLayer debugLayer;
[SerializeField]
PostProcessResources m_Resources;
// Some juggling needed to track down reference to the resource asset when loaded from asset
// bundle (guid conflict)
[NonSerialized]
PostProcessResources m_OldResources;
// UI states
[UnityEngine.Scripting.Preserve]
[SerializeField]
bool m_ShowToolkit;
[UnityEngine.Scripting.Preserve]
[SerializeField]
bool m_ShowCustomSorter;
/// <summary>
/// If <c>true</c>, it will stop applying post-processing effects just before color grading
/// is applied. This is used internally to export to EXR without color grading.
/// </summary>
public bool breakBeforeColorGrading = false;
// Pre-ordered custom user effects
// These are automatically populated and made to work properly with the serialization
// system AND the editor. Modify at your own risk.
/// <summary>
/// A wrapper around bundles to allow their serialization in lists.
/// </summary>
[Serializable]
public sealed class SerializedBundleRef
{
/// <summary>
/// The assembly qualified name used for serialization as we can't serialize the types
/// themselves.
/// </summary>
public string assemblyQualifiedName; // We only need this at init time anyway so it's fine
/// <summary>
/// A reference to the bundle itself.
/// </summary>
[NonSerialized]
public PostProcessBundle bundle; // Not serialized, is set/reset when deserialization kicks in
}
[SerializeField]
List<SerializedBundleRef> m_BeforeTransparentBundles;
[SerializeField]
List<SerializedBundleRef> m_BeforeStackBundles;
[SerializeField]
List<SerializedBundleRef> m_AfterStackBundles;
/// <summary>
/// Pre-ordered effects mapped to available injection points.
/// </summary>
public Dictionary<PostProcessEvent, List<SerializedBundleRef>> sortedBundles { get; private set; }
/// <summary>
/// The current flags set on the camera for the built-in render pipeline.
/// </summary>
public DepthTextureMode cameraDepthFlags { get; private set; }
// We need to keep track of bundle initialization because for some obscure reason, on
// assembly reload a MonoBehavior's Editor OnEnable will be called BEFORE the MonoBehavior's
// own OnEnable... So we'll use it to pre-init bundles if the layer inspector is opened and
// the component hasn't been enabled yet.
/// <summary>
/// Returns <c>true</c> if the bundles have been initialized properly.
/// </summary>
public bool haveBundlesBeenInited { get; private set; }
// Settings/Renderer bundles mapped to settings types
Dictionary<Type, PostProcessBundle> m_Bundles;
PropertySheetFactory m_PropertySheetFactory;
CommandBuffer m_LegacyCmdBufferBeforeReflections;
CommandBuffer m_LegacyCmdBufferBeforeLighting;
CommandBuffer m_LegacyCmdBufferOpaque;
CommandBuffer m_LegacyCmdBuffer;
Camera m_Camera;
PostProcessRenderContext m_CurrentContext;
LogHistogram m_LogHistogram;
bool m_SettingsUpdateNeeded = true;
bool m_IsRenderingInSceneView = false;
TargetPool m_TargetPool;
bool m_NaNKilled = false;
// Recycled list - used to reduce GC stress when gathering active effects in a bundle list
// on each frame
readonly List<PostProcessEffectRenderer> m_ActiveEffects = new List<PostProcessEffectRenderer>();
readonly List<RenderTargetIdentifier> m_Targets = new List<RenderTargetIdentifier>();
void OnEnable()
{
Init(null);
if (!haveBundlesBeenInited)
InitBundles();
m_LogHistogram = new LogHistogram();
m_PropertySheetFactory = new PropertySheetFactory();
m_TargetPool = new TargetPool();
debugLayer.OnEnable();
if (RuntimeUtilities.scriptableRenderPipelineActive)
return;
InitLegacy();
}
void InitLegacy()
{
m_LegacyCmdBufferBeforeReflections = new CommandBuffer { name = "Deferred Ambient Occlusion" };
m_LegacyCmdBufferBeforeLighting = new CommandBuffer { name = "Deferred Ambient Occlusion" };
m_LegacyCmdBufferOpaque = new CommandBuffer { name = "Opaque Only Post-processing" };
m_LegacyCmdBuffer = new CommandBuffer { name = "Post-processing" };
m_Camera = GetComponent<Camera>();
#if !UNITY_2019_1_OR_NEWER // OnRenderImage (below) implies forceIntoRenderTexture
m_Camera.forceIntoRenderTexture = true; // Needed when running Forward / LDR / No MSAA
#endif
m_Camera.AddCommandBuffer(CameraEvent.BeforeReflections, m_LegacyCmdBufferBeforeReflections);
m_Camera.AddCommandBuffer(CameraEvent.BeforeLighting, m_LegacyCmdBufferBeforeLighting);
m_Camera.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_LegacyCmdBufferOpaque);
m_Camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, m_LegacyCmdBuffer);
// Internal context used if no SRP is set
m_CurrentContext = new PostProcessRenderContext();
}
#if UNITY_2019_1_OR_NEWER
bool DynamicResolutionAllowsFinalBlitToCameraTarget()
{
return (!RuntimeUtilities.IsDynamicResolutionEnabled(m_Camera) || (ScalableBufferManager.heightScaleFactor == 1.0 && ScalableBufferManager.widthScaleFactor == 1.0));
}
#endif
#if UNITY_2019_1_OR_NEWER
// We always use a CommandBuffer to blit to the final render target
// OnRenderImage is used only to avoid the automatic blit from the RenderTexture of Camera.forceIntoRenderTexture to the actual target
#if !UNITY_EDITOR
[ImageEffectUsesCommandBuffer]
#endif
void OnRenderImage(RenderTexture src, RenderTexture dst)
{
if (finalBlitToCameraTarget && !m_CurrentContext.stereoActive && DynamicResolutionAllowsFinalBlitToCameraTarget())
RenderTexture.active = dst; // silence warning
else
Graphics.Blit(src, dst);
}
#endif
/// <summary>
/// Initializes this layer. If you create the layer via scripting you should always call
/// this method.
/// </summary>
/// <param name="resources">A reference to the resource asset</param>
public void Init(PostProcessResources resources)
{
if (resources != null) m_Resources = resources;
RuntimeUtilities.CreateIfNull(ref temporalAntialiasing);
RuntimeUtilities.CreateIfNull(ref subpixelMorphologicalAntialiasing);
RuntimeUtilities.CreateIfNull(ref fastApproximateAntialiasing);
RuntimeUtilities.CreateIfNull(ref dithering);
RuntimeUtilities.CreateIfNull(ref fog);
RuntimeUtilities.CreateIfNull(ref debugLayer);
}
/// <summary>
/// Initializes all the effect bundles. This is called automatically by the framework.
/// </summary>
public void InitBundles()
{
if (haveBundlesBeenInited)
return;
// Create these lists only once, the serialization system will take over after that
RuntimeUtilities.CreateIfNull(ref m_BeforeTransparentBundles);
RuntimeUtilities.CreateIfNull(ref m_BeforeStackBundles);
RuntimeUtilities.CreateIfNull(ref m_AfterStackBundles);
// Create a bundle for each effect type
m_Bundles = new Dictionary<Type, PostProcessBundle>();
foreach (var type in PostProcessManager.instance.settingsTypes.Keys)
{
var settings = (PostProcessEffectSettings)ScriptableObject.CreateInstance(type);
var bundle = new PostProcessBundle(settings);
m_Bundles.Add(type, bundle);
}
// Update sorted lists with newly added or removed effects in the assemblies
UpdateBundleSortList(m_BeforeTransparentBundles, PostProcessEvent.BeforeTransparent);
UpdateBundleSortList(m_BeforeStackBundles, PostProcessEvent.BeforeStack);
UpdateBundleSortList(m_AfterStackBundles, PostProcessEvent.AfterStack);
// Push all sorted lists in a dictionary for easier access
sortedBundles = new Dictionary<PostProcessEvent, List<SerializedBundleRef>>(new PostProcessEventComparer())
{
{ PostProcessEvent.BeforeTransparent, m_BeforeTransparentBundles },
{ PostProcessEvent.BeforeStack, m_BeforeStackBundles },
{ PostProcessEvent.AfterStack, m_AfterStackBundles }
};
// Done
haveBundlesBeenInited = true;
}
void UpdateBundleSortList(List<SerializedBundleRef> sortedList, PostProcessEvent evt)
{
// First get all effects associated with the injection point
var effects = m_Bundles.Where(kvp => kvp.Value.attribute.eventType == evt && !kvp.Value.attribute.builtinEffect)
.Select(kvp => kvp.Value)
.ToList();
// Remove types that don't exist anymore
sortedList.RemoveAll(x =>
{
string searchStr = x.assemblyQualifiedName;
return !effects.Exists(b => b.settings.GetType().AssemblyQualifiedName == searchStr);
});
// Add new ones
foreach (var effect in effects)
{
string typeName = effect.settings.GetType().AssemblyQualifiedName;
if (!sortedList.Exists(b => b.assemblyQualifiedName == typeName))
{
var sbr = new SerializedBundleRef { assemblyQualifiedName = typeName };
sortedList.Add(sbr);
}
}
// Link internal references
foreach (var effect in sortedList)
{
string typeName = effect.assemblyQualifiedName;
var bundle = effects.Find(b => b.settings.GetType().AssemblyQualifiedName == typeName);
effect.bundle = bundle;
}
}
void OnDisable()
{
// Have to check for null camera in case the user is doing back'n'forth between SRP and
// legacy
if (m_Camera != null)
{
if (m_LegacyCmdBufferBeforeReflections != null)
m_Camera.RemoveCommandBuffer(CameraEvent.BeforeReflections, m_LegacyCmdBufferBeforeReflections);
if (m_LegacyCmdBufferBeforeLighting != null)
m_Camera.RemoveCommandBuffer(CameraEvent.BeforeLighting, m_LegacyCmdBufferBeforeLighting);
if (m_LegacyCmdBufferOpaque != null)
m_Camera.RemoveCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_LegacyCmdBufferOpaque);
if (m_LegacyCmdBuffer != null)
m_Camera.RemoveCommandBuffer(CameraEvent.BeforeImageEffects, m_LegacyCmdBuffer);
}
temporalAntialiasing.Release();
m_LogHistogram.Release();
foreach (var bundle in m_Bundles.Values)
bundle.Release();
m_Bundles.Clear();
m_PropertySheetFactory.Release();
if (debugLayer != null)
debugLayer.OnDisable();
// Might be an issue if several layers are blending in the same frame...
TextureLerper.instance.Clear();
haveBundlesBeenInited = false;
}
// Called everytime the user resets the component from the inspector and more importantly
// the first time it's added to a GameObject. As we don't have added/removed event for
// components, this will do fine
void Reset()
{
volumeTrigger = transform;
}
void OnPreCull()
{
// Unused in scriptable render pipelines
if (RuntimeUtilities.scriptableRenderPipelineActive)
return;
if (m_Camera == null || m_CurrentContext == null)
InitLegacy();
// Postprocessing does tweak load/store actions when it uses render targets.
// But when using builtin render pipeline, Camera will silently apply viewport when setting render target,
// meaning that Postprocessing might think that it is rendering to fullscreen RT
// and use LoadAction.DontCare freely, which will ruin the RT if we are using viewport.
// It should actually check for having tiled architecture but this is not exposed to script,
// so we are checking for mobile as a good substitute
#if UNITY_2019_3_OR_NEWER
if (SystemInfo.usesLoadStoreActions)
#else
if (Application.isMobilePlatform)
#endif
{
Rect r = m_Camera.rect;
if (Mathf.Abs(r.x) > 1e-6f || Mathf.Abs(r.y) > 1e-6f || Mathf.Abs(1.0f - r.width) > 1e-6f || Mathf.Abs(1.0f - r.height) > 1e-6f)
{
Debug.LogWarning("When used with builtin render pipeline, Postprocessing package expects to be used on a fullscreen Camera.\nPlease note that using Camera viewport may result in visual artefacts or some things not working.", m_Camera);
}
}
// Resets the projection matrix from previous frame in case TAA was enabled.
// We also need to force reset the non-jittered projection matrix here as it's not done
// when ResetProjectionMatrix() is called and will break transparent rendering if TAA
// is switched off and the FOV or any other camera property changes.
if (m_CurrentContext.IsTemporalAntialiasingActive())
{
#if UNITY_2018_2_OR_NEWER
if (!m_Camera.usePhysicalProperties)
#endif
{
m_Camera.ResetProjectionMatrix();
m_Camera.nonJitteredProjectionMatrix = m_Camera.projectionMatrix;
#if (ENABLE_VR_MODULE && ENABLE_VR)
if (m_Camera.stereoEnabled)
{
m_Camera.ResetStereoProjectionMatrices();
if (m_Camera.stereoActiveEye == Camera.MonoOrStereoscopicEye.Right)
{
m_Camera.CopyStereoDeviceProjectionMatrixToNonJittered(Camera.StereoscopicEye.Right);
m_Camera.projectionMatrix = m_Camera.GetStereoNonJitteredProjectionMatrix(Camera.StereoscopicEye.Right);
m_Camera.nonJitteredProjectionMatrix = m_Camera.projectionMatrix;
m_Camera.SetStereoProjectionMatrix(Camera.StereoscopicEye.Right, m_Camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right));
}
else if (m_Camera.stereoActiveEye == Camera.MonoOrStereoscopicEye.Left || m_Camera.stereoActiveEye == Camera.MonoOrStereoscopicEye.Mono)
{
m_Camera.CopyStereoDeviceProjectionMatrixToNonJittered(Camera.StereoscopicEye.Left); // device to unjittered
m_Camera.projectionMatrix = m_Camera.GetStereoNonJitteredProjectionMatrix(Camera.StereoscopicEye.Left);
m_Camera.nonJitteredProjectionMatrix = m_Camera.projectionMatrix;
m_Camera.SetStereoProjectionMatrix(Camera.StereoscopicEye.Left, m_Camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left));
}
}
#endif
}
}
else
{
m_Camera.nonJitteredProjectionMatrix = m_Camera.projectionMatrix;
}
#if (ENABLE_VR_MODULE && ENABLE_VR)
if (m_Camera.stereoEnabled)
{
Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, XRSettings.renderViewportScale);
}
else
#endif
{
Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, 1.0f);
}
BuildCommandBuffers();
}
void OnPreRender()
{
// Unused in scriptable render pipelines
// Only needed for multi-pass stereo right eye
if (RuntimeUtilities.scriptableRenderPipelineActive ||
(m_Camera.stereoActiveEye != Camera.MonoOrStereoscopicEye.Right))
return;
BuildCommandBuffers();
}
static bool RequiresInitialBlit(Camera camera, PostProcessRenderContext context)
{
// [ImageEffectUsesCommandBuffer] is currently broken, FIXME
return true;
/*
#if UNITY_2019_1_OR_NEWER
if (camera.allowMSAA) // this shouldn't be necessary, but until re-tested on older Unity versions just do the blits
return true;
if (RuntimeUtilities.scriptableRenderPipelineActive) // Should never be called from SRP
return true;
return false;
#else
return true;
#endif
*/
}
void UpdateSrcDstForOpaqueOnly(ref int src, ref int dst, PostProcessRenderContext context, RenderTargetIdentifier cameraTarget, int opaqueOnlyEffectsRemaining)
{
if (src > -1)
context.command.ReleaseTemporaryRT(src);
context.source = context.destination;
src = dst;
if (opaqueOnlyEffectsRemaining == 1)
{
context.destination = cameraTarget;
}
else
{
dst = m_TargetPool.Get();
context.destination = dst;
context.GetScreenSpaceTemporaryRT(context.command, dst, 0, context.sourceFormat);
}
}
void BuildCommandBuffers()
{
var context = m_CurrentContext;
var sourceFormat = m_Camera.targetTexture ? m_Camera.targetTexture.format : (m_Camera.allowHDR ? RuntimeUtilities.defaultHDRRenderTextureFormat : RenderTextureFormat.Default);
if (!RuntimeUtilities.isFloatingPointFormat(sourceFormat))
m_NaNKilled = true;
context.Reset();
context.camera = m_Camera;
context.sourceFormat = sourceFormat;
// TODO: Investigate retaining command buffers on XR multi-pass right eye
m_LegacyCmdBufferBeforeReflections.Clear();
m_LegacyCmdBufferBeforeLighting.Clear();
m_LegacyCmdBufferOpaque.Clear();
m_LegacyCmdBuffer.Clear();
SetupContext(context);
context.command = m_LegacyCmdBufferOpaque;
TextureLerper.instance.BeginFrame(context);
UpdateVolumeSystem(context.camera, context.command);
// Lighting & opaque-only effects
var aoBundle = GetBundle<AmbientOcclusion>();
var aoSettings = aoBundle.CastSettings<AmbientOcclusion>();
var aoRenderer = aoBundle.CastRenderer<AmbientOcclusionRenderer>();
bool aoSupported = aoSettings.IsEnabledAndSupported(context);
bool aoAmbientOnly = aoRenderer.IsAmbientOnly(context);
bool isAmbientOcclusionDeferred = aoSupported && aoAmbientOnly;
bool isAmbientOcclusionOpaque = aoSupported && !aoAmbientOnly;
var ssrBundle = GetBundle<ScreenSpaceReflections>();
var ssrSettings = ssrBundle.settings;
var ssrRenderer = ssrBundle.renderer;
bool isScreenSpaceReflectionsActive = ssrSettings.IsEnabledAndSupported(context);
#if UNITY_2019_1_OR_NEWER
if (context.stereoActive)
context.UpdateSinglePassStereoState(context.IsTemporalAntialiasingActive(), aoSupported, isScreenSpaceReflectionsActive);
#endif
// Ambient-only AO is a special case and has to be done in separate command buffers
if (isAmbientOcclusionDeferred)
{
var ao = aoRenderer.Get();
// Render as soon as possible - should be done async in SRPs when available
context.command = m_LegacyCmdBufferBeforeReflections;
ao.RenderAmbientOnly(context);
// Composite with GBuffer right before the lighting pass
context.command = m_LegacyCmdBufferBeforeLighting;
ao.CompositeAmbientOnly(context);
}
else if (isAmbientOcclusionOpaque)
{
context.command = m_LegacyCmdBufferOpaque;
aoRenderer.Get().RenderAfterOpaque(context);
}
bool isFogActive = fog.IsEnabledAndSupported(context);
bool hasCustomOpaqueOnlyEffects = HasOpaqueOnlyEffects(context);
int opaqueOnlyEffects = 0;
opaqueOnlyEffects += isScreenSpaceReflectionsActive ? 1 : 0;
opaqueOnlyEffects += isFogActive ? 1 : 0;
opaqueOnlyEffects += hasCustomOpaqueOnlyEffects ? 1 : 0;
// This works on right eye because it is resolved/populated at runtime
var cameraTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.CameraTarget);
if (opaqueOnlyEffects > 0)
{
var cmd = m_LegacyCmdBufferOpaque;
context.command = cmd;
context.source = cameraTarget;
context.destination = cameraTarget;
int srcTarget = -1;
int dstTarget = -1;
UpdateSrcDstForOpaqueOnly(ref srcTarget, ref dstTarget, context, cameraTarget, opaqueOnlyEffects + 1); // + 1 for blit
if (RequiresInitialBlit(m_Camera, context) || opaqueOnlyEffects == 1)
{
cmd.BuiltinBlit(context.source, context.destination, RuntimeUtilities.copyStdMaterial, stopNaNPropagation ? 1 : 0);
UpdateSrcDstForOpaqueOnly(ref srcTarget, ref dstTarget, context, cameraTarget, opaqueOnlyEffects);
}
if (isScreenSpaceReflectionsActive)
{
ssrRenderer.RenderOrLog(context);
opaqueOnlyEffects--;
UpdateSrcDstForOpaqueOnly(ref srcTarget, ref dstTarget, context, cameraTarget, opaqueOnlyEffects);
}
if (isFogActive)
{
fog.Render(context);
opaqueOnlyEffects--;
UpdateSrcDstForOpaqueOnly(ref srcTarget, ref dstTarget, context, cameraTarget, opaqueOnlyEffects);
}
if (hasCustomOpaqueOnlyEffects)
RenderOpaqueOnly(context);
cmd.ReleaseTemporaryRT(srcTarget);
}
// Post-transparency stack
int tempRt = -1;
bool forceNanKillPass = (!m_NaNKilled && stopNaNPropagation && RuntimeUtilities.isFloatingPointFormat(sourceFormat));
bool vrSinglePassInstancingEnabled = context.stereoActive && context.numberOfEyes > 1 && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced;
if (!vrSinglePassInstancingEnabled && (RequiresInitialBlit(m_Camera, context) || forceNanKillPass))
{
int width = context.width;
#if UNITY_2019_1_OR_NEWER && ENABLE_VR_MODULE && ENABLE_VR
var xrDesc = XRSettings.eyeTextureDesc;
if (context.stereoActive && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
width = xrDesc.width;
#endif
tempRt = m_TargetPool.Get();
context.GetScreenSpaceTemporaryRT(m_LegacyCmdBuffer, tempRt, 0, sourceFormat, RenderTextureReadWrite.sRGB, FilterMode.Bilinear, width);
m_LegacyCmdBuffer.BuiltinBlit(cameraTarget, tempRt, RuntimeUtilities.copyStdMaterial, stopNaNPropagation ? 1 : 0);
if (!m_NaNKilled)
m_NaNKilled = stopNaNPropagation;
context.source = tempRt;
}
else
{
context.source = cameraTarget;
}
context.destination = cameraTarget;
#if UNITY_2019_1_OR_NEWER
if (finalBlitToCameraTarget && !m_CurrentContext.stereoActive && !RuntimeUtilities.scriptableRenderPipelineActive && DynamicResolutionAllowsFinalBlitToCameraTarget())
{
if (m_Camera.targetTexture)
{
context.destination = m_Camera.targetTexture.colorBuffer;
}
else
{
context.flip = true;
context.destination = Display.main.colorBuffer;
}
}
#endif
context.command = m_LegacyCmdBuffer;
Render(context);
if (tempRt > -1)
m_LegacyCmdBuffer.ReleaseTemporaryRT(tempRt);
}
void OnPostRender()
{
// Unused in scriptable render pipelines
if (RuntimeUtilities.scriptableRenderPipelineActive)
return;
if (m_CurrentContext.IsTemporalAntialiasingActive())
{
#if UNITY_2018_2_OR_NEWER
// TAA calls SetProjectionMatrix so if the camera projection mode was physical, it gets set to explicit. So we set it back to physical.
if (m_CurrentContext.physicalCamera)
m_Camera.usePhysicalProperties = true;
else
#endif
{
// The camera must be reset on precull and post render to avoid issues with alpha when toggling TAA.
m_Camera.ResetProjectionMatrix();
#if (ENABLE_VR_MODULE && ENABLE_VR)
if (m_CurrentContext.stereoActive)
{
if (RuntimeUtilities.isSinglePassStereoEnabled || m_Camera.stereoActiveEye == Camera.MonoOrStereoscopicEye.Right)
{
m_Camera.ResetStereoProjectionMatrices();
// copy the left eye onto the projection matrix so that we're using the correct projection matrix after calling m_Camera.ResetProjectionMatrix(); above.
if (XRSettings.stereoRenderingMode == XRSettings.StereoRenderingMode.MultiPass)
m_Camera.projectionMatrix = m_Camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left);
}
}
#endif
}
}
}
/// <summary>
/// Grabs the bundle for the given effect type.
/// </summary>
/// <typeparam name="T">An effect type.</typeparam>
/// <returns>The bundle for the effect of the given type.</returns>
public PostProcessBundle GetBundle<T>()
where T : PostProcessEffectSettings
{
return GetBundle(typeof(T));
}
/// <summary>
/// Grabs the bundle for the given effect type.
/// </summary>
/// <param name="settingsType">An effect type.</param>
/// <returns>The bundle for the effect of the given type.</returns>
public PostProcessBundle GetBundle(Type settingsType)
{
Assert.IsTrue(m_Bundles.ContainsKey(settingsType), "Invalid type");
return m_Bundles[settingsType];
}
/// <summary>
/// Gets the current settings for a given effect.
/// </summary>
/// <typeparam name="T">The type of effect to look for</typeparam>
/// <returns>The current state of an effect</returns>
public T GetSettings<T>()
where T : PostProcessEffectSettings
{
return GetBundle<T>().CastSettings<T>();
}
/// <summary>
/// Utility method to bake a multi-scale volumetric obscurance map for the current camera.
/// This will only work if ambient occlusion is active in the scene.
/// </summary>
/// <param name="cmd">The command buffer to use for rendering steps</param>
/// <param name="camera">The camera to render ambient occlusion for</param>
/// <param name="destination">The destination render target</param>
/// <param name="depthMap">The depth map to use. If <c>null</c>, it will use the depth map
/// from the given camera</param>
/// <param name="invert">Should the result be inverted?</param>
/// <param name="isMSAA">Should use MSAA?</param>
public void BakeMSVOMap(CommandBuffer cmd, Camera camera, RenderTargetIdentifier destination, RenderTargetIdentifier? depthMap, bool invert, bool isMSAA = false)
{
var bundle = GetBundle<AmbientOcclusion>();
var renderer = bundle.CastRenderer<AmbientOcclusionRenderer>().GetMultiScaleVO();
renderer.SetResources(m_Resources);
renderer.GenerateAOMap(cmd, camera, destination, depthMap, invert, isMSAA);
}
internal void OverrideSettings(List<PostProcessEffectSettings> baseSettings, float interpFactor)
{
// Go through all settings & overriden parameters for the given volume and lerp values
foreach (var settings in baseSettings)
{
if (!settings.active)
continue;
var target = GetBundle(settings.GetType()).settings;
int count = settings.parameters.Count;
for (int i = 0; i < count; i++)
{
var toParam = settings.parameters[i];
if (toParam.overrideState)
{
var fromParam = target.parameters[i];
fromParam.Interp(fromParam, toParam, interpFactor);
}
}
}
}
// In the legacy render loop you have to explicitely set flags on camera to tell that you
// need depth, depth+normals or motion vectors... This won't have any effect with most
// scriptable render pipelines.
void SetLegacyCameraFlags(PostProcessRenderContext context)
{
var flags = DepthTextureMode.None;
foreach (var bundle in m_Bundles)
{
if (bundle.Value.settings.IsEnabledAndSupported(context))
flags |= bundle.Value.renderer.GetCameraFlags();
}
// Special case for AA & lighting effects
if (context.IsTemporalAntialiasingActive())
flags |= temporalAntialiasing.GetCameraFlags();
if (fog.IsEnabledAndSupported(context))
flags |= fog.GetCameraFlags();
if (debugLayer.debugOverlay != DebugOverlay.None)
flags |= debugLayer.GetCameraFlags();
context.camera.depthTextureMode |= flags;
cameraDepthFlags = flags;
}
/// <summary>
/// This method should be called whenever you need to reset any temporal effect, e.g. when
/// doing camera cuts.
/// </summary>
public void ResetHistory()
{
foreach (var bundle in m_Bundles)
bundle.Value.ResetHistory();
temporalAntialiasing.ResetHistory();
}
/// <summary>
/// Checks if this layer has any active opaque-only effect.
/// </summary>
/// <param name="context">The current render context</param>
/// <returns><c>true</c> if opaque-only effects are active, <c>false</c> otherwise</returns>
public bool HasOpaqueOnlyEffects(PostProcessRenderContext context)
{
return HasActiveEffects(PostProcessEvent.BeforeTransparent, context);
}
/// <summary>
/// Checks if this layer has any active effect at the given injection point.
/// </summary>
/// <param name="evt">The injection point to look for</param>
/// <param name="context">The current render context</param>
/// <returns><c>true</c> if any effect at the given injection point is active, <c>false</c>
/// otherwise</returns>
public bool HasActiveEffects(PostProcessEvent evt, PostProcessRenderContext context)
{
var list = sortedBundles[evt];
foreach (var item in list)
{
bool enabledAndSupported = item.bundle.settings.IsEnabledAndSupported(context);
if (context.isSceneView)
{
if (item.bundle.attribute.allowInSceneView && enabledAndSupported)
return true;
}
else if (enabledAndSupported)
{
return true;
}
}
return false;
}
void SetupContext(PostProcessRenderContext context)
{
// Juggling required when a scene with post processing is loaded from an asset bundle
// See #1148230
// Additional !RuntimeUtilities.isValidResources() to fix #1262826
// The static member s_Resources is unset by addressable. The code is ill formed as it
// is not made to handle multiple scene.
if (m_OldResources != m_Resources || !RuntimeUtilities.isValidResources())
{
RuntimeUtilities.UpdateResources(m_Resources);
m_OldResources = m_Resources;
}
m_IsRenderingInSceneView = context.camera.cameraType == CameraType.SceneView;
context.isSceneView = m_IsRenderingInSceneView;
context.resources = m_Resources;
context.propertySheets = m_PropertySheetFactory;
context.debugLayer = debugLayer;
context.antialiasing = antialiasingMode;
context.temporalAntialiasing = temporalAntialiasing;
context.logHistogram = m_LogHistogram;
#if UNITY_2018_2_OR_NEWER
context.physicalCamera = context.camera.usePhysicalProperties;
#endif
SetLegacyCameraFlags(context);
// Prepare debug overlay
debugLayer.SetFrameSize(context.width, context.height);
// Unsafe to keep this around but we need it for OnGUI events for debug views
// Will be removed eventually
m_CurrentContext = context;
}
/// <summary>
/// Updates the state of the volume system. This should be called before any other
/// post-processing method when running in a scriptable render pipeline. You don't need to
/// call this method when running in one of the builtin pipelines.
/// </summary>
/// <param name="cam">The currently rendering camera.</param>
/// <param name="cmd">A command buffer to fill.</param>
public void UpdateVolumeSystem(Camera cam, CommandBuffer cmd)
{
if (m_SettingsUpdateNeeded)
{
cmd.BeginSample("VolumeBlending");
PostProcessManager.instance.UpdateSettings(this, cam);
cmd.EndSample("VolumeBlending");
m_TargetPool.Reset();
// TODO: fix me once VR support is in SRP
// Needed in SRP so that _RenderViewportScaleFactor isn't 0
if (RuntimeUtilities.scriptableRenderPipelineActive)
Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, 1f);
}
m_SettingsUpdateNeeded = false;
}
/// <summary>
/// Renders effects in the <see cref="PostProcessEvent.BeforeTransparent"/> bucket. You
/// should call <see cref="HasOpaqueOnlyEffects"/> before calling this method as it won't
/// automatically blit source into destination if no opaque-only effect is active.
/// </summary>
/// <param name="context">The current post-processing context.</param>
public void RenderOpaqueOnly(PostProcessRenderContext context)
{
if (RuntimeUtilities.scriptableRenderPipelineActive)
SetupContext(context);
TextureLerper.instance.BeginFrame(context);
// Update & override layer settings first (volume blending), will only be done once per
// frame, either here or in Render() if there isn't any opaque-only effect to render.
// TODO: should be removed, keeping this here for older SRPs
UpdateVolumeSystem(context.camera, context.command);
RenderList(sortedBundles[PostProcessEvent.BeforeTransparent], context, "OpaqueOnly");
}
/// <summary>
/// Renders all effects not in the <see cref="PostProcessEvent.BeforeTransparent"/> bucket.
/// </summary>
/// <param name="context">The current post-processing context.</param>
public void Render(PostProcessRenderContext context)
{
if (RuntimeUtilities.scriptableRenderPipelineActive)
SetupContext(context);
TextureLerper.instance.BeginFrame(context);
var cmd = context.command;
// Update & override layer settings first (volume blending) if the opaque only pass
// hasn't been called this frame.
// TODO: should be removed, keeping this here for older SRPs
UpdateVolumeSystem(context.camera, context.command);
// Do a NaN killing pass if needed
int lastTarget = -1;
RenderTargetIdentifier cameraTexture = context.source;
#if UNITY_2019_1_OR_NEWER
if (context.stereoActive && context.numberOfEyes > 1 && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
{
cmd.SetSinglePassStereo(SinglePassStereoMode.None);
cmd.DisableShaderKeyword("UNITY_SINGLE_PASS_STEREO");
}