forked from Unity-Technologies/PostProcessing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostProcessManager.cs
More file actions
428 lines (347 loc) · 15.1 KB
/
PostProcessManager.cs
File metadata and controls
428 lines (347 loc) · 15.1 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
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering.PostProcessing
{
// Singleton used to tracks all existing volumes in the scene
// TODO: Deal with 2D volumes !
public sealed class PostProcessManager
{
static PostProcessManager s_Instance;
public static PostProcessManager instance
{
get
{
if (s_Instance == null)
s_Instance = new PostProcessManager();
return s_Instance;
}
}
const int k_MaxLayerCount = 32; // Max amount of layers available in Unity
readonly Dictionary<int, List<PostProcessVolume>> m_SortedVolumes;
readonly List<PostProcessVolume> m_Volumes;
readonly Dictionary<int, bool> m_SortNeeded;
readonly List<PostProcessEffectSettings> m_BaseSettings;
readonly List<Collider> m_TempColliders;
public readonly Dictionary<Type, PostProcessAttribute> settingsTypes;
PostProcessManager()
{
m_SortedVolumes = new Dictionary<int, List<PostProcessVolume>>();
m_Volumes = new List<PostProcessVolume>();
m_SortNeeded = new Dictionary<int, bool>();
m_BaseSettings = new List<PostProcessEffectSettings>();
m_TempColliders = new List<Collider>(5);
settingsTypes = new Dictionary<Type, PostProcessAttribute>();
ReloadBaseTypes();
}
#if UNITY_EDITOR
// Called every time Unity recompile scripts in the editor. We need this to keep track of
// any new custom effect the user might add to the project
[UnityEditor.Callbacks.DidReloadScripts]
static void OnEditorReload()
{
instance.ReloadBaseTypes();
}
#endif
void CleanBaseTypes()
{
settingsTypes.Clear();
foreach (var settings in m_BaseSettings)
RuntimeUtilities.Destroy(settings);
m_BaseSettings.Clear();
}
// This will be called only once at runtime and everytime script reload kicks-in in the
// editor as we need to keep track of any compatible post-processing effects in the project
void ReloadBaseTypes()
{
CleanBaseTypes();
// Rebuild the base type map
var types = RuntimeUtilities.GetAllAssemblyTypes()
.Where(
t => t.IsSubclassOf(typeof(PostProcessEffectSettings))
&& t.IsDefined(typeof(PostProcessAttribute), false)
&& !t.IsAbstract
);
foreach (var type in types)
{
settingsTypes.Add(type, type.GetAttribute<PostProcessAttribute>());
// Create an instance for each effect type, these will be used for the lowest
// priority global volume as we need a default state when exiting volume ranges
var inst = (PostProcessEffectSettings)ScriptableObject.CreateInstance(type);
inst.SetAllOverridesTo(true, false);
m_BaseSettings.Add(inst);
}
}
// Gets a list of all volumes currently affecting the given layer. Results aren't sorted.
// Volume with weight of 0 or no profile set will be skipped. Results list won't be cleared.
public void GetActiveVolumes(PostProcessLayer layer, List<PostProcessVolume> results, bool skipDisabled = true, bool skipZeroWeight = true)
{
// If no trigger is set, only global volumes will have influence
int mask = layer.volumeLayer.value;
var volumeTrigger = layer.volumeTrigger;
bool onlyGlobal = volumeTrigger == null;
var triggerPos = onlyGlobal ? Vector3.zero : volumeTrigger.position;
// Sort the cached volume list(s) for the given layer mask if needed and return it
var volumes = GrabVolumes(mask);
// Traverse all volumes
foreach (var volume in volumes)
{
// Skip disabled volumes and volumes without any data or weight
if ((skipDisabled && !volume.enabled) || volume.profileRef == null || (skipZeroWeight && volume.weight <= 0f))
continue;
// Global volume always have influence
if (volume.isGlobal)
{
results.Add(volume);
continue;
}
if (onlyGlobal)
continue;
// If volume isn't global and has no collider, skip it as it's useless
var colliders = m_TempColliders;
volume.GetComponents(colliders);
if (colliders.Count == 0)
continue;
// Find closest distance to volume, 0 means it's inside it
float closestDistanceSqr = float.PositiveInfinity;
foreach (var collider in colliders)
{
if (!collider.enabled)
continue;
var closestPoint = collider.ClosestPoint(triggerPos); // 5.6-only API
var d = ((closestPoint - triggerPos) / 2f).sqrMagnitude;
if (d < closestDistanceSqr)
closestDistanceSqr = d;
}
colliders.Clear();
float blendDistSqr = volume.blendDistance * volume.blendDistance;
// Check for influence
if (closestDistanceSqr <= blendDistSqr)
results.Add(volume);
}
}
public PostProcessVolume GetHighestPriorityVolume(PostProcessLayer layer)
{
if (layer == null)
throw new ArgumentNullException("layer");
return GetHighestPriorityVolume(layer.volumeLayer);
}
public PostProcessVolume GetHighestPriorityVolume(LayerMask mask)
{
float highestPriority = float.NegativeInfinity;
PostProcessVolume output = null;
List<PostProcessVolume> volumes;
if (m_SortedVolumes.TryGetValue(mask, out volumes))
{
foreach (var volume in volumes)
{
if (volume.priority > highestPriority)
{
highestPriority = volume.priority;
output = volume;
}
}
}
return output;
}
public PostProcessVolume QuickVolume(int layer, float priority, params PostProcessEffectSettings[] settings)
{
var gameObject = new GameObject()
{
name = "Quick Volume",
layer = layer,
hideFlags = HideFlags.HideAndDontSave
};
var volume = gameObject.AddComponent<PostProcessVolume>();
volume.priority = priority;
volume.isGlobal = true;
var profile = volume.profile;
foreach (var s in settings)
{
Assert.IsNotNull(s, "Trying to create a volume with null effects");
profile.AddSettings(s);
}
return volume;
}
internal void SetLayerDirty(int layer)
{
Assert.IsTrue(layer >= 0 && layer <= k_MaxLayerCount, "Invalid layer bit");
foreach (var kvp in m_SortedVolumes)
{
var mask = kvp.Key;
if ((mask & (1 << layer)) != 0)
m_SortNeeded[mask] = true;
}
}
internal void UpdateVolumeLayer(PostProcessVolume volume, int prevLayer, int newLayer)
{
Assert.IsTrue(prevLayer >= 0 && prevLayer <= k_MaxLayerCount, "Invalid layer bit");
Unregister(volume, prevLayer);
Register(volume, newLayer);
}
void Register(PostProcessVolume volume, int layer)
{
m_Volumes.Add(volume);
// Look for existing cached layer masks and add it there if needed
foreach (var kvp in m_SortedVolumes)
{
var mask = kvp.Key;
if ((mask & (1 << layer)) != 0)
kvp.Value.Add(volume);
}
SetLayerDirty(layer);
}
internal void Register(PostProcessVolume volume)
{
int layer = volume.gameObject.layer;
Register(volume, layer);
}
void Unregister(PostProcessVolume volume, int layer)
{
m_Volumes.Remove(volume);
foreach (var kvp in m_SortedVolumes)
{
var mask = kvp.Key;
// Skip layer masks this volume doesn't belong to
if ((mask & (1 << layer)) == 0)
continue;
kvp.Value.Remove(volume);
}
}
internal void Unregister(PostProcessVolume volume)
{
int layer = volume.gameObject.layer;
Unregister(volume, layer);
}
// Faster version of OverrideSettings to force replace values in the global state
void ReplaceData(PostProcessLayer postProcessLayer)
{
foreach (var settings in m_BaseSettings)
{
var target = postProcessLayer.GetBundle(settings.GetType()).settings;
target.Reset(settings);
}
}
internal void UpdateSettings(PostProcessLayer postProcessLayer, Camera camera)
{
// Reset to base state
ReplaceData(postProcessLayer);
// If no trigger is set, only global volumes will have influence
int mask = postProcessLayer.volumeLayer.value;
var volumeTrigger = postProcessLayer.volumeTrigger;
bool onlyGlobal = volumeTrigger == null;
var triggerPos = onlyGlobal ? Vector3.zero : volumeTrigger.position;
// Sort the cached volume list(s) for the given layer mask if needed and return it
var volumes = GrabVolumes(mask);
// Traverse all volumes
foreach (var volume in volumes)
{
#if UNITY_EDITOR
// Skip volumes that aren't in the scene currently displayed in the scene view
if (!IsVolumeRenderedByCamera(volume, camera))
continue;
#endif
// Skip disabled volumes and volumes without any data or weight
if (!volume.enabled || volume.profileRef == null || volume.weight <= 0f)
continue;
var settings = volume.profileRef.settings;
// Global volume always have influence
if (volume.isGlobal)
{
postProcessLayer.OverrideSettings(settings, Mathf.Clamp01(volume.weight));
continue;
}
if (onlyGlobal)
continue;
// If volume isn't global and has no collider, skip it as it's useless
var colliders = m_TempColliders;
volume.GetComponents(colliders);
if (colliders.Count == 0)
continue;
// Find closest distance to volume, 0 means it's inside it
float closestDistanceSqr = float.PositiveInfinity;
foreach (var collider in colliders)
{
if (!collider.enabled)
continue;
var closestPoint = collider.ClosestPoint(triggerPos); // 5.6-only API
var d = ((closestPoint - triggerPos) / 2f).sqrMagnitude;
if (d < closestDistanceSqr)
closestDistanceSqr = d;
}
colliders.Clear();
float blendDistSqr = volume.blendDistance * volume.blendDistance;
// Volume has no influence, ignore it
// Note: Volume doesn't do anything when `closestDistanceSqr = blendDistSqr` but
// we can't use a >= comparison as blendDistSqr could be set to 0 in which
// case volume would have total influence
if (closestDistanceSqr > blendDistSqr)
continue;
// Volume has influence
float interpFactor = 1f;
if (blendDistSqr > 0f)
interpFactor = 1f - (closestDistanceSqr / blendDistSqr);
// No need to clamp01 the interpolation factor as it'll always be in [0;1[ range
postProcessLayer.OverrideSettings(settings, interpFactor * Mathf.Clamp01(volume.weight));
}
}
List<PostProcessVolume> GrabVolumes(LayerMask mask)
{
List<PostProcessVolume> list;
if (!m_SortedVolumes.TryGetValue(mask, out list))
{
// New layer mask detected, create a new list and cache all the volumes that belong
// to this mask in it
list = new List<PostProcessVolume>();
foreach (var volume in m_Volumes)
{
if ((mask & (1 << volume.gameObject.layer)) == 0)
continue;
list.Add(volume);
m_SortNeeded[mask] = true;
}
m_SortedVolumes.Add(mask, list);
}
// Check sorting state
bool sortNeeded;
if (m_SortNeeded.TryGetValue(mask, out sortNeeded) && sortNeeded)
{
m_SortNeeded[mask] = false;
SortByPriority(list);
}
return list;
}
// Custom insertion sort. First sort will be slower but after that it'll be faster than
// using List<T>.Sort() which is also unstable by nature.
// Sort order is ascending.
static void SortByPriority(List<PostProcessVolume> volumes)
{
Assert.IsNotNull(volumes, "Trying to sort volumes of non-initialized layer");
for (int i = 1; i < volumes.Count; i++)
{
var temp = volumes[i];
int j = i - 1;
while (j >= 0 && volumes[j].priority > temp.priority)
{
volumes[j + 1] = volumes[j];
j--;
}
volumes[j + 1] = temp;
}
}
static bool IsVolumeRenderedByCamera(PostProcessVolume volume, Camera camera)
{
#if UNITY_2018_3_OR_NEWER && UNITY_EDITOR
// If the current camera have a custom scene then the camera is rendering that scene,
// otherwise the camera is rendering the scenes in the SceneManager.
var customScene = camera.scene;
return customScene.IsValid()
? UnityEditor.SceneManagement.EditorSceneManager.IsGameObjectInScene(volume.gameObject, customScene)
: UnityEditor.SceneManagement.EditorSceneManager.IsGameObjectInMainScenes(volume.gameObject);
#else
return true;
#endif
}
}
}