-
Notifications
You must be signed in to change notification settings - Fork 870
Expand file tree
/
Copy pathProbeReferenceVolume.cs
More file actions
2229 lines (1898 loc) · 92.7 KB
/
Copy pathProbeReferenceVolume.cs
File metadata and controls
2229 lines (1898 loc) · 92.7 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.Diagnostics;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine.Profiling;
using UnityEngine.SceneManagement;
using Chunk = UnityEngine.Rendering.ProbeBrickPool.BrickChunkAlloc;
using Brick = UnityEngine.Rendering.ProbeBrickIndex.Brick;
using Unity.Collections;
using Unity.Profiling;
using Unity.Mathematics;
using UnityEngine.Experimental.Rendering;
#if UNITY_EDITOR
using System.Linq.Expressions;
using UnityEditor;
#endif
namespace UnityEngine.Rendering
{
internal static class SceneExtensions
{
static PropertyInfo s_SceneGUID = typeof(Scene).GetProperty("guid", BindingFlags.NonPublic | BindingFlags.Instance);
public static string GetGUID(this Scene scene)
{
Debug.Assert(s_SceneGUID != null, "Reflection for scene GUID failed");
return (string)s_SceneGUID.GetValue(scene);
}
}
/// <summary>
/// Initialization parameters for the probe volume system.
/// </summary>
public struct ProbeVolumeSystemParameters
{
/// <summary>
/// The memory budget determining the size of the textures containing SH data.
/// </summary>
public ProbeVolumeTextureMemoryBudget memoryBudget;
/// <summary>
/// The memory budget determining the size of the textures used for blending between scenarios.
/// </summary>
public ProbeVolumeBlendingTextureMemoryBudget blendingMemoryBudget;
/// <summary>
/// The <see cref="ProbeVolumeSHBands"/>
/// </summary>
public ProbeVolumeSHBands shBands;
/// <summary>True if APV should support lighting scenarios.</summary>
public bool supportScenarios;
/// <summary>True if APV should support lighting scenario blending.</summary>
public bool supportScenarioBlending;
/// <summary>True if APV should support streaming of cell data to the GPU.</summary>
public bool supportGPUStreaming;
/// <summary>True if APV should support streaming of cell data from the disk.</summary>
public bool supportDiskStreaming;
/// <summary>
/// The shader used to visualize the probes in the debug view.
/// </summary>
[Obsolete("This field is not used anymore.")]
public Shader probeDebugShader;
/// <summary>
/// The shader used to visualize the way probes are sampled for a single pixel in the debug view.
/// </summary>
[Obsolete("This field is not used anymore.")]
public Shader probeSamplingDebugShader;
/// <summary>
/// The debug texture used to display probe weight in the debug view.
/// </summary>
[Obsolete("This field is not used anymore.")]
public Texture probeSamplingDebugTexture;
/// <summary>
/// The debug mesh used to visualize the way probes are sampled for a single pixel in the debug view.
/// </summary>
[Obsolete("This field is not used anymore.")]
public Mesh probeSamplingDebugMesh;
/// <summary>
/// The shader used to visualize probes virtual offset in the debug view.
/// </summary>
[Obsolete("This field is not used anymore.")]
public Shader offsetDebugShader;
/// <summary>
/// The shader used to visualize APV fragmentation.
/// </summary>
[Obsolete("This field is not used anymore.")]
public Shader fragmentationDebugShader;
/// <summary>
/// The compute shader used to interpolate between two lighting scenarios.
/// Set to null if blending is not supported.
/// </summary>
[Obsolete("This field is not used anymore.")]
public ComputeShader scenarioBlendingShader;
/// <summary>
/// The compute shader used to upload streamed data to the GPU.
/// </summary>
[Obsolete("This field is not used anymore.")]
public ComputeShader streamingUploadShader;
/// <summary>
/// The <see cref="ProbeVolumeSceneData"/>
/// </summary>
[Obsolete("This field is not used anymore.")]
public ProbeVolumeSceneData sceneData;
/// <summary>True if APV is able to show runtime debug information.</summary>
[Obsolete("This field is not used anymore. Used with the current Shader Stripping Settings. #from(2023.3)")]
public bool supportsRuntimeDebug;
}
internal struct ProbeVolumeShadingParameters
{
public float normalBias;
public float viewBias;
public bool scaleBiasByMinDistanceBetweenProbes;
public float samplingNoise;
public float weight;
public APVLeakReductionMode leakReductionMode;
public int frameIndexForNoise;
public float reflNormalizationLowerClamp;
public float reflNormalizationUpperClamp;
public float skyOcclusionIntensity;
public bool skyOcclusionShadingDirection;
public int regionCount;
public uint4 regionLayerMasks;
public Vector3 worldOffset;
}
/// <summary>
/// Possible values for the probe volume memory budget (determines the size of the textures used).
/// </summary>
[Serializable]
public enum ProbeVolumeTextureMemoryBudget
{
/// <summary>Low Budget</summary>
MemoryBudgetLow = 512,
/// <summary>Medium Budget</summary>
MemoryBudgetMedium = 1024,
/// <summary>High Budget</summary>
MemoryBudgetHigh = 2048,
}
/// <summary>
/// Possible values for the probe volume scenario blending memory budget (determines the size of the textures used).
/// </summary>
[Serializable]
public enum ProbeVolumeBlendingTextureMemoryBudget
{
/// <summary>Low Budget</summary>
MemoryBudgetLow = 128,
/// <summary>Medium Budget</summary>
MemoryBudgetMedium = 256,
/// <summary>High Budget</summary>
MemoryBudgetHigh = 512,
}
/// <summary>
/// Number of Spherical Harmonics bands that are used with Probe Volumes
/// </summary>
[Serializable]
public enum ProbeVolumeSHBands
{
/// <summary>Up to the L1 band of Spherical Harmonics</summary>
SphericalHarmonicsL1 = 1,
/// <summary>Up to the L2 band of Spherical Harmonics</summary>
SphericalHarmonicsL2 = 2,
}
/// <summary>
/// The reference volume for the Adaptive Probe Volumes system. This defines the structure in which volume assets are loaded into. There must be only one, hence why it follow a singleton pattern.
/// </summary>
public partial class ProbeReferenceVolume
{
[Serializable]
internal struct IndirectionEntryInfo
{
public Vector3Int positionInBricks;
public int minSubdiv;
public Vector3Int minBrickPos;
public Vector3Int maxBrickPosPlusOne;
public bool hasMinMax; // should be removed, only kept for migration
public bool hasOnlyBiggerBricks; // True if it has only bricks that are bigger than the entry itself
}
[Serializable]
internal class CellDesc
{
public Vector3Int position;
public int index;
public int probeCount;
public int minSubdiv;
public int indexChunkCount;
public int shChunkCount;
public int bricksCount;
// This is data that is generated at bake time to not having to re-analyzing the content of the cell for the indirection buffer.
// This is not technically part of the descriptor of the cell but it needs to be here because it's computed at bake time and needs
// to be serialized with the rest of the cell.
public IndirectionEntryInfo[] indirectionEntryInfo;
public override string ToString()
{
return $"Index = {index} position = {position}";
}
}
internal class CellData
{
// Shared Data
public NativeArray<byte> validityNeighMaskData;
public NativeArray<ushort> skyOcclusionDataL0L1 { get; internal set; }
public NativeArray<byte> skyShadingDirectionIndices { get; internal set; }
// Scenario Data
public struct PerScenarioData
{
// L0/L1 Data
public NativeArray<ushort> shL0L1RxData;
public NativeArray<byte> shL1GL1RyData;
public NativeArray<byte> shL1BL1RzData;
// Optional L2 Data
public NativeArray<byte> shL2Data_0;
public NativeArray<byte> shL2Data_1;
public NativeArray<byte> shL2Data_2;
public NativeArray<byte> shL2Data_3;
// 4 unorm per probe, 1 for each occluded light
public NativeArray<byte> probeOcclusion;
}
public Dictionary<string, PerScenarioData> scenarios = new Dictionary<string, PerScenarioData>();
// Brick data.
public NativeArray<Brick> bricks { get; internal set; }
// Support Data
public NativeArray<Vector3> probePositions { get; internal set; }
public NativeArray<float> touchupVolumeInteraction { get; internal set; } // Only used by a specific debug view.
public NativeArray<Vector3> offsetVectors { get; internal set; }
public NativeArray<float> validity { get; internal set; }
public NativeArray<byte> layer { get; internal set; } // Only used by a specific debug view.
public void CleanupPerScenarioData(in PerScenarioData data)
{
if (data.shL0L1RxData.IsCreated)
{
data.shL0L1RxData.Dispose();
data.shL1GL1RyData.Dispose();
data.shL1BL1RzData.Dispose();
}
if (data.shL2Data_0.IsCreated)
{
data.shL2Data_0.Dispose();
data.shL2Data_1.Dispose();
data.shL2Data_2.Dispose();
data.shL2Data_3.Dispose();
}
if (data.probeOcclusion.IsCreated)
{
data.probeOcclusion.Dispose();
}
}
public void Cleanup(bool cleanScenarioList)
{
// GPU Data. Will not exist if disk streaming is enabled.
if (validityNeighMaskData.IsCreated)
{
validityNeighMaskData.Dispose();
validityNeighMaskData = default;
foreach (var scenario in scenarios.Values)
CleanupPerScenarioData(scenario);
}
// When using disk streaming, we don't want to clear this list as it's the only place where we know which scenarios are available for the cell
// This is ok because the scenario data isn't instantiated here.
if (cleanScenarioList)
scenarios.Clear();
// Bricks and support data. May not exist with disk streaming.
if (bricks.IsCreated)
{
bricks.Dispose();
bricks = default;
}
if (skyOcclusionDataL0L1.IsCreated)
{
skyOcclusionDataL0L1.Dispose();
skyOcclusionDataL0L1 = default;
}
if (skyShadingDirectionIndices.IsCreated)
{
skyShadingDirectionIndices.Dispose();
skyShadingDirectionIndices = default;
}
if (probePositions.IsCreated)
{
probePositions.Dispose();
probePositions = default;
}
if (touchupVolumeInteraction.IsCreated)
{
touchupVolumeInteraction.Dispose();
touchupVolumeInteraction = default;
}
if (validity.IsCreated)
{
validity.Dispose();
validity = default;
}
if (layer.IsCreated)
{
layer.Dispose();
layer = default;
}
if (offsetVectors.IsCreated)
{
offsetVectors.Dispose();
offsetVectors = default;
}
}
}
internal class CellPoolInfo
{
public List<Chunk> chunkList = new List<Chunk>();
public int shChunkCount;
public void Clear()
{
chunkList.Clear();
}
}
internal class CellIndexInfo
{
public int[] flatIndicesInGlobalIndirection = null;
public ProbeBrickIndex.CellIndexUpdateInfo updateInfo;
public bool indexUpdated;
public IndirectionEntryInfo[] indirectionEntryInfo;
public int indexChunkCount;
public void Clear()
{
flatIndicesInGlobalIndirection = null;
updateInfo = default(ProbeBrickIndex.CellIndexUpdateInfo);
indexUpdated = false;
indirectionEntryInfo = null;
}
}
internal class CellBlendingInfo
{
public List<Chunk> chunkList = new List<Chunk>();
public float blendingScore;
public float blendingFactor;
public bool blending;
public void MarkUpToDate() => blendingScore = float.MaxValue;
public bool IsUpToDate() => blendingScore == float.MaxValue;
public void ForceReupload() => blendingFactor = -1.0f;
public bool ShouldReupload() => blendingFactor == -1.0f;
public void Prioritize() => blendingFactor = -2.0f;
public bool ShouldPrioritize() => blendingFactor == -2.0f;
public void Clear()
{
chunkList.Clear();
blendingScore = 0;
blendingFactor = 0;
blending = false;
}
}
internal class CellStreamingInfo
{
public CellStreamingRequest request = null;
public CellStreamingRequest blendingRequest0 = null;
public CellStreamingRequest blendingRequest1 = null;
public float streamingScore;
public bool IsStreaming()
{
return request != null && request.IsStreaming();
}
public bool IsBlendingStreaming()
{
return blendingRequest0 != null && blendingRequest0.IsStreaming()
|| blendingRequest1 != null && blendingRequest1.IsStreaming();
}
public void Clear()
{
request = null;
blendingRequest0 = null;
blendingRequest1 = null;
streamingScore = 0;
}
}
[DebuggerDisplay("Index = {desc.index} Loaded = {loaded}")]
internal class Cell : IComparable<Cell>
{
// Baked data (cell descriptor and baked probe data read from disk).
public CellDesc desc;
public CellData data;
// Runtime info.
public CellPoolInfo poolInfo = new CellPoolInfo();
public CellIndexInfo indexInfo = new CellIndexInfo();
public CellBlendingInfo blendingInfo = new CellBlendingInfo();
public CellStreamingInfo streamingInfo = new CellStreamingInfo();
public int referenceCount = 0;
public bool loaded; // "Loaded" means the streaming system decided the cell should be loaded. It does not mean it's ready for GPU consumption (because of blending or disk streaming)
public CellData.PerScenarioData scenario0;
public CellData.PerScenarioData scenario1;
public bool hasTwoScenarios;
public CellInstancedDebugProbes debugProbes;
public int CompareTo(Cell other)
{
if (streamingInfo.streamingScore < other.streamingInfo.streamingScore)
return -1;
else if (streamingInfo.streamingScore > other.streamingInfo.streamingScore)
return 1;
else
return 0;
}
public bool UpdateCellScenarioData(string scenario0, string scenario1)
{
if(!data.scenarios.TryGetValue(scenario0, out this.scenario0))
{
return false;
}
hasTwoScenarios = false;
if (!string.IsNullOrEmpty(scenario1))
{
if (data.scenarios.TryGetValue(scenario1, out this.scenario1))
hasTwoScenarios = true;
}
return true;
}
public void Clear()
{
desc = null;
data = null;
poolInfo.Clear();
indexInfo.Clear();
blendingInfo.Clear();
streamingInfo.Clear();
referenceCount = 0;
loaded = false;
scenario0 = default;
scenario1 = default;
hasTwoScenarios = false;
debugProbes = null;
}
}
internal struct Volume : IEquatable<Volume>
{
internal Vector3 corner;
internal Vector3 X; // the vectors are NOT normalized, their length determines the size of the box
internal Vector3 Y;
internal Vector3 Z;
internal float maxSubdivisionMultiplier;
internal float minSubdivisionMultiplier;
public Volume(Matrix4x4 trs, float maxSubdivision, float minSubdivision)
{
X = trs.GetColumn(0);
Y = trs.GetColumn(1);
Z = trs.GetColumn(2);
corner = (Vector3)trs.GetColumn(3) - X * 0.5f - Y * 0.5f - Z * 0.5f;
this.maxSubdivisionMultiplier = maxSubdivision;
this.minSubdivisionMultiplier = minSubdivision;
}
public Volume(Vector3 corner, Vector3 X, Vector3 Y, Vector3 Z, float maxSubdivision = 1, float minSubdivision = 0)
{
this.corner = corner;
this.X = X;
this.Y = Y;
this.Z = Z;
this.maxSubdivisionMultiplier = maxSubdivision;
this.minSubdivisionMultiplier = minSubdivision;
}
public Volume(Volume copy)
{
X = copy.X;
Y = copy.Y;
Z = copy.Z;
corner = copy.corner;
maxSubdivisionMultiplier = copy.maxSubdivisionMultiplier;
minSubdivisionMultiplier = copy.minSubdivisionMultiplier;
}
public Volume(Bounds bounds)
{
var size = bounds.size;
corner = bounds.center - size * 0.5f;
X = new Vector3(size.x, 0, 0);
Y = new Vector3(0, size.y, 0);
Z = new Vector3(0, 0, size.z);
maxSubdivisionMultiplier = minSubdivisionMultiplier = 0;
}
public Bounds CalculateAABB()
{
Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
for (int x = 0; x < 2; x++)
{
for (int y = 0; y < 2; y++)
{
for (int z = 0; z < 2; z++)
{
Vector3 dir = new Vector3(x, y, z);
Vector3 pt = corner
+ X * dir.x
+ Y * dir.y
+ Z * dir.z;
min = Vector3.Min(min, pt);
max = Vector3.Max(max, pt);
}
}
}
return new Bounds((min + max) / 2, max - min);
}
public void CalculateCenterAndSize(out Vector3 center, out Vector3 size)
{
size = new Vector3(X.magnitude, Y.magnitude, Z.magnitude);
center = corner + X * 0.5f + Y * 0.5f + Z * 0.5f;
}
public void Transform(Matrix4x4 trs)
{
corner = trs.MultiplyPoint(corner);
X = trs.MultiplyVector(X);
Y = trs.MultiplyVector(Y);
Z = trs.MultiplyVector(Z);
}
public override string ToString()
{
return $"Corner: {corner}, X: {X}, Y: {Y}, Z: {Z}, MaxSubdiv: {maxSubdivisionMultiplier}";
}
public bool Equals(Volume other)
{
return corner == other.corner
&& X == other.X
&& Y == other.Y
&& Z == other.Z
&& minSubdivisionMultiplier == other.minSubdivisionMultiplier
&& maxSubdivisionMultiplier == other.maxSubdivisionMultiplier;
}
}
internal struct RefVolTransform
{
public Vector3 posWS;
public Quaternion rot;
public float scale;
}
/// <summary>
/// The resources that are bound to the runtime shaders for sampling Adaptive Probe Volume data.
/// </summary>
public struct RuntimeResources
{
/// <summary>
/// Index data to fetch the correct location in the Texture3D.
/// </summary>
public ComputeBuffer index;
/// <summary>
/// Indices of the various index buffers for each cell.
/// </summary>
public ComputeBuffer cellIndices;
/// <summary>
/// Texture containing Spherical Harmonics L0 band data and first coefficient of L1_R.
/// </summary>
public RenderTexture L0_L1rx;
/// <summary>
/// Texture containing the second channel of Spherical Harmonics L1 band data and second coefficient of L1_R.
/// </summary>
public RenderTexture L1_G_ry;
/// <summary>
/// Texture containing the second channel of Spherical Harmonics L1 band data and third coefficient of L1_R.
/// </summary>
public RenderTexture L1_B_rz;
/// <summary>
/// Texture containing the first coefficient of Spherical Harmonics L2 band data and first channel of the fifth.
/// </summary>
public RenderTexture L2_0;
/// <summary>
/// Texture containing the second coefficient of Spherical Harmonics L2 band data and second channel of the fifth.
/// </summary>
public RenderTexture L2_1;
/// <summary>
/// Texture containing the third coefficient of Spherical Harmonics L2 band data and third channel of the fifth.
/// </summary>
public RenderTexture L2_2;
/// <summary>
/// Texture containing the fourth coefficient of Spherical Harmonics L2 band data.
/// </summary>
public RenderTexture L2_3;
/// <summary>
/// Texture containing 4 light occlusion coefficients for each probe.
/// </summary>
public RenderTexture ProbeOcclusion;
/// <summary>
/// Texture containing packed validity binary data for the neighbourhood of each probe. Only used when L1. Otherwise this info is stored
/// in the alpha channel of L2_3.
/// </summary>
public RenderTexture Validity;
/// <summary>
/// Texture containing Sky Occlusion SH data (only L0 and L1 band)
/// </summary>
public RenderTexture SkyOcclusionL0L1;
/// <summary>
/// Texture containing Sky Shading direction indices
/// </summary>
public RenderTexture SkyShadingDirectionIndices;
/// <summary>
/// Precomputed table of shading directions for sky occlusion shading.
/// </summary>
public ComputeBuffer SkyPrecomputedDirections;
/// <summary>
/// Precomputed table of sampling mask for quality leak reduction.
/// </summary>
public ComputeBuffer QualityLeakReductionData;
}
bool m_IsInitialized = false;
bool m_SupportScenarios = false;
bool m_SupportScenarioBlending = false;
bool m_ForceNoDiskStreaming = false;
bool m_SupportDiskStreaming = false;
bool m_SupportGPUStreaming = false;
bool m_UseStreamingAssets = true;
float m_MinBrickSize;
int m_MaxSubdivision;
Vector3 m_ProbeOffset;
ProbeBrickPool m_Pool;
ProbeBrickIndex m_Index;
ProbeGlobalIndirection m_CellIndices;
ProbeBrickBlendingPool m_BlendingPool;
List<Chunk> m_TmpSrcChunks = new List<Chunk>();
float[] m_PositionOffsets = new float[ProbeBrickPool.kBrickProbeCountPerDim];
Bounds m_CurrGlobalBounds = new Bounds();
internal Bounds globalBounds { get { return m_CurrGlobalBounds; } set { m_CurrGlobalBounds = value; } }
internal Dictionary<int, Cell> cells = new Dictionary<int, Cell>();
ObjectPool<Cell> m_CellPool = new ObjectPool<Cell>(x => x.Clear(), null, false);
ProbeBrickPool.DataLocation m_TemporaryDataLocation;
int m_TemporaryDataLocationMemCost;
#pragma warning disable 618
[Obsolete("This field is only kept for migration purpose.")]
internal ProbeVolumeSceneData sceneData; // Kept for migration
#pragma warning restore 618
// We need to keep track the area, in cells, that is currently loaded. The index buffer will cover even unloaded areas, but we want to avoid sampling outside those areas.
Vector3Int minLoadedCellPos = new Vector3Int(int.MaxValue, int.MaxValue, int.MaxValue);
Vector3Int maxLoadedCellPos = new Vector3Int(int.MinValue, int.MinValue, int.MinValue);
/// <summary>
/// The input to the retrieveExtraDataAction action.
/// </summary>
public struct ExtraDataActionInput
{
// Empty, but defined to make this future proof without having to change public API
}
/// <summary>
/// An action that is used by the SRP to retrieve extra data that was baked together with the bake
/// </summary>
public Action<ExtraDataActionInput> retrieveExtraDataAction;
/// <summary>
/// An action that is used by the SRP to perform checks every frame during baking.
/// </summary>
public Action checksDuringBakeAction = null;
// Information of the probe volume scenes that is being loaded (if one is pending)
Dictionary<string, (ProbeVolumeBakingSet, List<int>)> m_PendingScenesToBeLoaded = new Dictionary<string, (ProbeVolumeBakingSet, List<int>)>();
// Information on probes we need to remove.
Dictionary<string, List<int>> m_PendingScenesToBeUnloaded = new Dictionary<string, List<int>>();
// Information of the probe volume scenes that is being loaded (if one is pending)
List<string> m_ActiveScenes = new List<string>();
ProbeVolumeBakingSet m_CurrentBakingSet = null;
ProbeVolumeBakingSet m_LazyBakingSet = null;
bool m_NeedLoadAsset = false;
bool m_ProbeReferenceVolumeInit = false;
bool m_EnabledBySRP = false;
bool m_VertexSampling = false;
/// <summary>Is Probe Volume initialized.</summary>
public bool isInitialized => m_IsInitialized;
internal bool enabledBySRP => m_EnabledBySRP;
internal bool vertexSampling => m_VertexSampling;
internal bool hasUnloadedCells => m_ToBeLoadedCells.size != 0;
internal bool supportLightingScenarios => m_SupportScenarios;
internal bool supportScenarioBlending => m_SupportScenarioBlending;
internal bool gpuStreamingEnabled => m_SupportGPUStreaming;
internal bool diskStreamingEnabled => m_SupportDiskStreaming && !m_ForceNoDiskStreaming;
/// <summary>
/// Whether APV stores occlusion for mixed lights.
/// </summary>
public bool probeOcclusion
{
get => m_CurrentBakingSet ? m_CurrentBakingSet.bakedProbeOcclusion : false;
}
/// <summary>
/// Whether APV handles sky dynamically (with baked sky occlusion) or fully statically.
/// </summary>
public bool skyOcclusion
{
get => m_CurrentBakingSet ? m_CurrentBakingSet.bakedSkyOcclusion : false;
}
/// <summary>
/// Bake sky shading direction.
/// </summary>
public bool skyOcclusionShadingDirection
{
get => m_CurrentBakingSet ? m_CurrentBakingSet.bakedSkyShadingDirection : false;
}
bool useRenderingLayers => m_CurrentBakingSet.bakedMaskCount != 1;
bool m_NeedsIndexRebuild = false;
bool m_HasChangedIndex = false;
int m_CBShaderID = Shader.PropertyToID("ShaderVariablesProbeVolumes");
ProbeVolumeTextureMemoryBudget m_MemoryBudget;
ProbeVolumeBlendingTextureMemoryBudget m_BlendingMemoryBudget;
ProbeVolumeSHBands m_SHBands;
/// <summary>
/// The <see cref="ProbeVolumeSHBands"/>
/// </summary>
public ProbeVolumeSHBands shBands => m_SHBands;
internal bool clearAssetsOnVolumeClear = false;
/// <summary>The active baking set.</summary>
public ProbeVolumeBakingSet currentBakingSet => m_CurrentBakingSet;
/// <summary>The active lighting scenario.</summary>
public string lightingScenario
{
get => m_CurrentBakingSet ? m_CurrentBakingSet.lightingScenario : null;
set
{
SetActiveScenario(value);
}
}
/// <summary>The lighting scenario APV is blending toward.</summary>
public string otherScenario
{
get => m_CurrentBakingSet ? m_CurrentBakingSet.otherScenario : null;
}
/// <summary>The blending factor currently used to blend probe data. A value of 0 means blending is not active.</summary>
public float scenarioBlendingFactor
{
get => m_CurrentBakingSet ? m_CurrentBakingSet.scenarioBlendingFactor : 0.0f;
set
{
if (m_CurrentBakingSet != null)
m_CurrentBakingSet.BlendLightingScenario(m_CurrentBakingSet.otherScenario, value);
}
}
static internal string GetSceneGUID(Scene scene) => scene.GetGUID();
internal void SetActiveScenario(string scenario, bool verbose = true)
{
if (m_CurrentBakingSet != null)
m_CurrentBakingSet.SetActiveScenario(scenario, verbose);
}
/// <summary>Allows smooth transitions between two lighting scenarios. This only affects the runtime data used for lighting.</summary>
/// <param name="otherScenario">The name of the scenario to load.</param>
/// <param name="blendingFactor">The factor used to interpolate between the active scenario and otherScenario. Accepted values range from 0 to 1 and will progressively blend from the active scenario to otherScenario.</param>
public void BlendLightingScenario(string otherScenario, float blendingFactor)
{
if (m_CurrentBakingSet != null)
m_CurrentBakingSet.BlendLightingScenario(otherScenario, blendingFactor);
}
internal static string defaultLightingScenario = "Default";
/// <summary>
/// Get the memory budget for the Probe Volume system.
/// </summary>
public ProbeVolumeTextureMemoryBudget memoryBudget => m_MemoryBudget;
static ProbeReferenceVolume _instance = new ProbeReferenceVolume();
internal List<ProbeVolumePerSceneData> perSceneDataList { get; private set; } = new List<ProbeVolumePerSceneData>();
internal void RegisterPerSceneData(ProbeVolumePerSceneData data)
{
if (!perSceneDataList.Contains(data))
{
perSceneDataList.Add(data);
// Registration can happen before APV (or even the current pipeline) is initialized, so in this case we need to delay the init.
if (m_IsInitialized)
data.Initialize();
}
}
/// <summary>
/// Setting a BakingSet while it is uninitialized schedules it to be set after initialization.
/// </summary>
/// <param name="bakingSet">BakingSet to set.</param>
/// <returns>Returns true when scheduled.</returns>
internal bool ScheduleBakingSet(ProbeVolumeBakingSet bakingSet)
{
if (m_IsInitialized)
{
return false;
}
m_LazyBakingSet = bakingSet;
return true;
}
/// <summary>
/// Set the scheduled BakingSet if it exists.
/// </summary>
/// <returns>Returns true if the scheduling is executed.</returns>
internal bool ProcessScheduledBakingSet()
{
if (m_LazyBakingSet == null)
{
return false;
}
SetActiveBakingSet(m_LazyBakingSet);
m_LazyBakingSet = null;
return true;
}
/// <summary>
/// Loads the baking set the given scene is part of if it exists.
/// </summary>
/// <param name="scene">The scene for which to load the baking set.</param>
public void SetActiveScene(Scene scene)
{
if (TryGetPerSceneData(GetSceneGUID(scene), out var perSceneData))
SetActiveBakingSet(perSceneData.serializedBakingSet);
}
/// <summary>
/// Set the currently active baking set.
/// Can be used when loading additively two scenes belonging to different baking sets to control which one is active.
/// </summary>
/// <param name="bakingSet">The baking set to load.</param>
public void SetActiveBakingSet(ProbeVolumeBakingSet bakingSet)
{
if (m_CurrentBakingSet == bakingSet)
return;
if (ScheduleBakingSet(bakingSet))
{
return;
}
foreach (var data in perSceneDataList)
data.QueueSceneRemoval();
UnloadBakingSet();
SetBakingSetAsCurrent(bakingSet);
if (m_CurrentBakingSet != null)
{
foreach (var data in perSceneDataList)
data.QueueSceneLoading();
}
}
void SetBakingSetAsCurrent(ProbeVolumeBakingSet bakingSet)
{
m_CurrentBakingSet = bakingSet;
// Can happen when you have only one scene loaded and you remove it from any baking set.
if (m_CurrentBakingSet != null)
{
// Delay first time init to after baking set is loaded to ensure we allocate what's needed
InitProbeReferenceVolume();
m_CurrentBakingSet.Initialize(m_UseStreamingAssets);
m_CurrGlobalBounds = m_CurrentBakingSet.globalBounds;
SetSubdivisionDimensions(bakingSet.minBrickSize, bakingSet.maxSubdivision, bakingSet.bakedProbeOffset);
m_NeedsIndexRebuild = true;
}
}
internal void RegisterBakingSet(ProbeVolumePerSceneData data)
{
if (m_CurrentBakingSet == null)
{
SetBakingSetAsCurrent(data.serializedBakingSet);
}
}
internal void UnloadBakingSet()
{
// Need to make sure everything is unloaded before killing the baking set ref (we need it to unload cell CPU data).
PerformPendingOperations();
if (m_CurrentBakingSet != null)
m_CurrentBakingSet.Cleanup();
m_CurrentBakingSet = null;
m_CurrGlobalBounds = new Bounds();
// Restart pool from zero to avoid unnecessary memory consumption when going from a big to a small scene.
if (m_ScratchBufferPool != null)
{
m_ScratchBufferPool.Cleanup();
m_ScratchBufferPool = null;
}
}
internal void UnregisterPerSceneData(ProbeVolumePerSceneData data)
{
perSceneDataList.Remove(data);
if (perSceneDataList.Count == 0)
UnloadBakingSet();
}
internal bool TryGetPerSceneData(string sceneGUID, out ProbeVolumePerSceneData perSceneData)
{
foreach (var data in perSceneDataList)
{
if (GetSceneGUID(data.gameObject.scene) == sceneGUID)
{
perSceneData = data;
return true;
}
}
perSceneData = null;
return false;
}
internal float indexFragmentationRate { get => m_ProbeReferenceVolumeInit ? m_Index.fragmentationRate : 0; }
/// <summary>