-
Notifications
You must be signed in to change notification settings - Fork 870
Expand file tree
/
Copy pathProbeGIBaking.cs
More file actions
2092 lines (1742 loc) · 90.6 KB
/
ProbeGIBaking.cs
File metadata and controls
2092 lines (1742 loc) · 90.6 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 System.Reflection;
using System.Threading;
using Unity.Collections;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine.LightTransport;
using UnityEngine.SceneManagement;
using Brick = UnityEngine.Rendering.ProbeBrickIndex.Brick;
using IndirectionEntryInfo = UnityEngine.Rendering.ProbeReferenceVolume.IndirectionEntryInfo;
using TouchupVolumeWithBoundsList = System.Collections.Generic.List<(UnityEngine.Rendering.ProbeReferenceVolume.Volume obb, UnityEngine.Bounds aabb, UnityEngine.Rendering.ProbeAdjustmentVolume volume)>;
namespace UnityEngine.Rendering
{
struct BakingCell
{
public Vector3Int position;
public int index;
public Brick[] bricks;
public Vector3[] probePositions;
public SphericalHarmonicsL2[] sh;
public byte[,] validityNeighbourMask;
public Vector4[] skyOcclusionDataL0L1;
public byte[] skyShadingDirectionIndices;
public float[] validity;
public Vector4[] probeOcclusion;
public byte[] layerValidity;
public Vector3[] offsetVectors;
public float[] touchupVolumeInteraction;
public int minSubdiv;
public int indexChunkCount;
public int shChunkCount;
public IndirectionEntryInfo[] indirectionEntryInfo;
public int[] probeIndices;
public Bounds bounds;
internal void ComputeBounds(float cellSize)
{
var center = new Vector3((position.x + 0.5f) * cellSize, (position.y + 0.5f) * cellSize, (position.z + 0.5f) * cellSize);
bounds = new Bounds(center, new Vector3(cellSize, cellSize, cellSize));
}
internal TouchupVolumeWithBoundsList SelectIntersectingAdjustmentVolumes(TouchupVolumeWithBoundsList touchupVolumesAndBounds)
{
// Find the subset of touchup volumes that will be considered for this cell.
// Capacity of the list to cover the worst case.
var localTouchupVolumes = new TouchupVolumeWithBoundsList(touchupVolumesAndBounds.Count);
foreach (var touchup in touchupVolumesAndBounds)
{
if (touchup.aabb.Intersects(bounds))
localTouchupVolumes.Add(touchup);
}
return localTouchupVolumes;
}
static internal void CompressSH(ref SphericalHarmonicsL2 shv, float intensityScale, bool clearForDilation)
{
// Compress the range of all coefficients but the DC component to [0..1]
// Upper bounds taken from http://ppsloan.org/publications/Sig20_Advances.pptx
// Divide each coefficient by DC*f to get to [-1,1] where f is from slide 33
for (int rgb = 0; rgb < 3; ++rgb)
{
for (int k = 0; k < 9; ++k)
shv[rgb, k] *= intensityScale;
var l0 = shv[rgb, 0];
if (l0 == 0.0f)
{
shv[rgb, 0] = 0.0f;
for (int k = 1; k < 9; ++k)
shv[rgb, k] = 0.5f;
}
else if (clearForDilation)
{
for (int k = 0; k < 9; ++k)
shv[rgb, k] = 0.0f;
}
else
{
// TODO: We're working on irradiance instead of radiance coefficients
// Add safety margin 2 to avoid out-of-bounds values
float l1scale = 2.0f; // Should be: 3/(2*sqrt(3)) * 2, but rounding to 2 to issues we are observing.
float l2scale = 3.5777088f; // 4/sqrt(5) * 2
// L_1^m
shv[rgb, 1] = shv[rgb, 1] / (l0 * l1scale * 2.0f) + 0.5f;
shv[rgb, 2] = shv[rgb, 2] / (l0 * l1scale * 2.0f) + 0.5f;
shv[rgb, 3] = shv[rgb, 3] / (l0 * l1scale * 2.0f) + 0.5f;
// L_2^-2
shv[rgb, 4] = shv[rgb, 4] / (l0 * l2scale * 2.0f) + 0.5f;
shv[rgb, 5] = shv[rgb, 5] / (l0 * l2scale * 2.0f) + 0.5f;
shv[rgb, 6] = shv[rgb, 6] / (l0 * l2scale * 2.0f) + 0.5f;
shv[rgb, 7] = shv[rgb, 7] / (l0 * l2scale * 2.0f) + 0.5f;
shv[rgb, 8] = shv[rgb, 8] / (l0 * l2scale * 2.0f) + 0.5f;
for (int coeff = 1; coeff < 9; ++coeff)
shv[rgb, coeff] = Mathf.Clamp01(shv[rgb, coeff]);
}
}
}
static internal void DecompressSH(ref SphericalHarmonicsL2 shv)
{
for (int rgb = 0; rgb < 3; ++rgb)
{
var l0 = shv[rgb, 0];
// See CompressSH
float l1scale = 2.0f;
float l2scale = 3.5777088f;
// L_1^m
shv[rgb, 1] = (shv[rgb, 1] - 0.5f) * (l0 * l1scale * 2.0f);
shv[rgb, 2] = (shv[rgb, 2] - 0.5f) * (l0 * l1scale * 2.0f);
shv[rgb, 3] = (shv[rgb, 3] - 0.5f) * (l0 * l1scale * 2.0f);
// L_2^-2
shv[rgb, 4] = (shv[rgb, 4] - 0.5f) * (l0 * l2scale * 2.0f);
shv[rgb, 5] = (shv[rgb, 5] - 0.5f) * (l0 * l2scale * 2.0f);
shv[rgb, 6] = (shv[rgb, 6] - 0.5f) * (l0 * l2scale * 2.0f);
shv[rgb, 7] = (shv[rgb, 7] - 0.5f) * (l0 * l2scale * 2.0f);
shv[rgb, 8] = (shv[rgb, 8] - 0.5f) * (l0 * l2scale * 2.0f);
}
}
void SetSHCoefficients(int i, SphericalHarmonicsL2 value, float intensityScale, float valid, in ProbeDilationSettings dilationSettings)
{
bool clearForDilation = dilationSettings.enableDilation && dilationSettings.dilationDistance > 0.0f && valid > dilationSettings.dilationValidityThreshold;
CompressSH(ref value, intensityScale, clearForDilation);
SphericalHarmonicsL2Utils.SetL0(ref sh[i], new Vector3(value[0, 0], value[1, 0], value[2, 0]));
SphericalHarmonicsL2Utils.SetL1R(ref sh[i], new Vector3(value[0, 3], value[0, 1], value[0, 2]));
SphericalHarmonicsL2Utils.SetL1G(ref sh[i], new Vector3(value[1, 3], value[1, 1], value[1, 2]));
SphericalHarmonicsL2Utils.SetL1B(ref sh[i], new Vector3(value[2, 3], value[2, 1], value[2, 2]));
SphericalHarmonicsL2Utils.SetCoefficient(ref sh[i], 4, new Vector3(value[0, 4], value[1, 4], value[2, 4]));
SphericalHarmonicsL2Utils.SetCoefficient(ref sh[i], 5, new Vector3(value[0, 5], value[1, 5], value[2, 5]));
SphericalHarmonicsL2Utils.SetCoefficient(ref sh[i], 6, new Vector3(value[0, 6], value[1, 6], value[2, 6]));
SphericalHarmonicsL2Utils.SetCoefficient(ref sh[i], 7, new Vector3(value[0, 7], value[1, 7], value[2, 7]));
SphericalHarmonicsL2Utils.SetCoefficient(ref sh[i], 8, new Vector3(value[0, 8], value[1, 8], value[2, 8]));
}
void ReadAdjustmentVolumes(ProbeVolumeBakingSet bakingSet, BakingBatch bakingBatch, TouchupVolumeWithBoundsList localTouchupVolumes, int i, float validity,
ref byte validityMask, out bool invalidatedProbe, out float intensityScale, out uint? skyShadingDirectionOverride)
{
invalidatedProbe = false;
intensityScale = 1.0f;
skyShadingDirectionOverride = null;
foreach (var touchup in localTouchupVolumes)
{
var touchupBound = touchup.aabb;
var touchupVolume = touchup.volume;
// We check a small box around the probe to give some leniency (a couple of centimeters).
var probeBounds = new Bounds(probePositions[i], new Vector3(0.02f, 0.02f, 0.02f));
if (touchupVolume.IntersectsVolume(touchup.obb, touchup.aabb, probeBounds))
{
if (touchupVolume.mode == ProbeAdjustmentVolume.Mode.InvalidateProbes)
{
invalidatedProbe = true;
if (validity < 0.05f) // We just want to add probes that were not already invalid or close to.
{
// We check as below 1 but bigger than 0 in the debug shader, so any value <1 will do to signify touched up.
touchupVolumeInteraction[i] = 0.5f;
bakingBatch.forceInvalidatedProbesAndTouchupVols[probePositions[i]] = touchupBound;
}
break;
}
else if (touchupVolume.mode == ProbeAdjustmentVolume.Mode.OverrideValidityThreshold)
{
float thresh = (1.0f - touchupVolume.overriddenDilationThreshold);
// The 1.0f + is used to determine the action (debug shader tests above 1), then we add the threshold to be able to retrieve it in debug phase.
touchupVolumeInteraction[i] = 1.0f + thresh;
bakingBatch.customDilationThresh[(index, i)] = thresh;
}
else if (touchupVolume.mode == ProbeAdjustmentVolume.Mode.OverrideSkyDirection && bakingSet.skyOcclusion && bakingSet.skyOcclusionShadingDirection)
{
skyShadingDirectionOverride = AdaptiveProbeVolumes.SkyOcclusionBaker.EncodeSkyShadingDirection(touchupVolume.skyDirection);
}
else if (touchupVolume.mode == ProbeAdjustmentVolume.Mode.OverrideRenderingLayerMask && bakingSet.useRenderingLayers)
{
switch (touchupVolume.renderingLayerMaskOperation)
{
case ProbeAdjustmentVolume.RenderingLayerMaskOperation.Override:
validityMask = touchupVolume.renderingLayerMask;
break;
case ProbeAdjustmentVolume.RenderingLayerMaskOperation.Add:
validityMask |= touchupVolume.renderingLayerMask;
break;
case ProbeAdjustmentVolume.RenderingLayerMaskOperation.Remove:
validityMask &= (byte)(~touchupVolume.renderingLayerMask);
break;
}
}
if (touchupVolume.mode == ProbeAdjustmentVolume.Mode.IntensityScale)
intensityScale = touchupVolume.intensityScale;
if (intensityScale != 1.0f)
touchupVolumeInteraction[i] = 2.0f + intensityScale;
}
}
if (validity < 0.05f && bakingBatch.invalidatedPositions.ContainsKey(probePositions[i]) && bakingBatch.invalidatedPositions[probePositions[i]])
{
if (!bakingBatch.forceInvalidatedProbesAndTouchupVols.ContainsKey(probePositions[i]))
bakingBatch.forceInvalidatedProbesAndTouchupVols.Add(probePositions[i], new Bounds());
invalidatedProbe = true;
}
}
internal void SetBakedData(ProbeVolumeBakingSet bakingSet, BakingBatch bakingBatch, TouchupVolumeWithBoundsList localTouchupVolumes, int i, int probeIndex,
in SphericalHarmonicsL2 sh, float validity, NativeArray<uint> renderingLayerMasks, NativeArray<Vector3> virtualOffsets, NativeArray<Vector4> skyOcclusion, NativeArray<uint> skyDirection, NativeArray<Vector4> probeOcclusion)
{
byte layerValidityMask = (byte)(renderingLayerMasks.IsCreated ? renderingLayerMasks[probeIndex] : 0);
ReadAdjustmentVolumes(bakingSet, bakingBatch, localTouchupVolumes, i, validity, ref layerValidityMask, out var invalidatedProbe, out var intensityScale, out var skyShadingDirectionOverride);
SetSHCoefficients(i, sh, intensityScale, validity, bakingSet.settings.dilationSettings);
if (virtualOffsets.IsCreated)
offsetVectors[i] = virtualOffsets[probeIndex];
if (skyOcclusion.IsCreated)
{
skyOcclusionDataL0L1[i] = skyOcclusion[probeIndex];
if (skyDirection.IsCreated)
skyShadingDirectionIndices[i] = (byte)(skyShadingDirectionOverride ?? skyDirection[probeIndex]);
}
if (renderingLayerMasks.IsCreated)
layerValidity[i] = layerValidityMask;
float currValidity = invalidatedProbe ? 1.0f : validity;
byte currValidityNeighbourMask = 255;
this.validity[i] = currValidity;
for (int l = 0; l < APVDefinitions.probeMaxRegionCount; l++)
validityNeighbourMask[l, i] = currValidityNeighbourMask;
if (probeOcclusion.IsCreated)
this.probeOcclusion[i] = probeOcclusion[probeIndex];
}
internal int GetBakingHashCode()
{
int hash = position.GetHashCode();
hash = hash * 23 + minSubdiv.GetHashCode();
hash = hash * 23 + indexChunkCount.GetHashCode();
hash = hash * 23 + shChunkCount.GetHashCode();
foreach (var brick in bricks)
{
hash = hash * 23 + brick.position.GetHashCode();
hash = hash * 23 + brick.subdivisionLevel.GetHashCode();
}
return hash;
}
}
class BakingBatch : IDisposable
{
public Dictionary<int, HashSet<string>> cellIndex2SceneReferences = new();
public List<BakingCell> cells = new();
// Used to retrieve probe data from it's position in order to fix seams
public NativeHashMap<int, int> positionToIndex;
// Allow to get a mapping to subdiv level with the unique positions. It stores the minimum subdiv level found for a given position.
// Can be probably done cleaner.
public NativeHashMap<int, int> uniqueBrickSubdiv;
// Mapping for explicit invalidation, whether it comes from the auto finding of occluders or from the touch up volumes
// TODO: This is not used yet. Will soon.
public Dictionary<Vector3, bool> invalidatedPositions = new();
// Utilities to compute unique probe position hash
Vector3Int maxBrickCount;
float inverseScale;
Vector3 offset;
public Dictionary<(int, int), float> customDilationThresh = new();
public Dictionary<Vector3, Bounds> forceInvalidatedProbesAndTouchupVols = new();
private GIContributors? m_Contributors;
public GIContributors contributors
{
get
{
if (!m_Contributors.HasValue)
m_Contributors = GIContributors.Find(GIContributors.ContributorFilter.All);
return m_Contributors.Value;
}
}
private BakingBatch() { }
public BakingBatch(Vector3Int cellCount, ProbeReferenceVolume refVolume)
{
maxBrickCount = cellCount * ProbeReferenceVolume.CellSize(refVolume.GetMaxSubdivision());
inverseScale = ProbeBrickPool.kBrickCellCount / refVolume.MinBrickSize();
offset = refVolume.ProbeOffset();
// Initialize NativeHashMaps with reasonable initial capacity
// Using a larger capacity to reduce allocations during baking
positionToIndex = new NativeHashMap<int, int>(100000, Allocator.Persistent);
uniqueBrickSubdiv = new NativeHashMap<int, int>(100000, Allocator.Persistent);
}
public void Dispose()
{
if (positionToIndex.IsCreated)
positionToIndex.Dispose();
if (uniqueBrickSubdiv.IsCreated)
uniqueBrickSubdiv.Dispose();
}
public int GetProbePositionHash(Vector3 position)
{
var brickPosition = Vector3Int.RoundToInt((position - offset) * inverseScale); // Inverse of op in ConvertBricksToPositions()
return GetBrickPositionHash(brickPosition);
}
public int GetBrickPositionHash(Vector3Int brickPosition)
{
return brickPosition.x + brickPosition.y * maxBrickCount.x + brickPosition.z * maxBrickCount.x * maxBrickCount.y;
}
public int GetSubdivLevelAt(Vector3 position) => uniqueBrickSubdiv[GetProbePositionHash(position)];
}
/// <summary>
/// Class responsible for baking of Probe Volumes
/// </summary>
[InitializeOnLoad]
public partial class AdaptiveProbeVolumes
{
internal abstract class BakingProfiling<T> where T : Enum
{
protected virtual string LogFile => null; // Override in child classes to write profiling data to disk
protected virtual bool ShowProgressBar => true;
protected T prevStage;
bool disposed = false;
static float globalProgress = 0.0f;
public float GetProgress(T stage) => (int)(object)stage / (float)(int)(object)GetLastStep();
void UpdateProgressBar(T stage)
{
if (!ShowProgressBar)
return;
if (EqualityComparer<T>.Default.Equals(stage, GetLastStep()))
{
globalProgress = 0.0f;
EditorUtility.ClearProgressBar();
}
else
{
globalProgress = Mathf.Max(GetProgress(stage), globalProgress); // prevent progress from going back
EditorUtility.DisplayProgressBar("Baking Adaptive Probe Volumes", stage.ToString(), globalProgress);
}
}
public abstract T GetLastStep();
public BakingProfiling(T stage, ref T currentStage)
{
if (LogFile != null && EqualityComparer<T>.Default.Equals(currentStage, GetLastStep()))
{
Profiling.Profiler.logFile = LogFile;
Profiling.Profiler.enableBinaryLog = true;
Profiling.Profiler.enabled = true;
}
prevStage = currentStage;
currentStage = stage;
UpdateProgressBar(stage);
if (LogFile != null)
Profiling.Profiler.BeginSample(stage.ToString());
}
public void OnDispose(ref T currentStage)
{
if (disposed) return;
disposed = true;
if (LogFile != null)
Profiling.Profiler.EndSample();
UpdateProgressBar(prevStage);
currentStage = prevStage;
if (LogFile != null && EqualityComparer<T>.Default.Equals(currentStage, GetLastStep()))
{
Profiling.Profiler.enabled = false;
Profiling.Profiler.logFile = null;
}
}
}
internal class BakingSetupProfiling : BakingProfiling<BakingSetupProfiling.Stages>, IDisposable
{
//protected override string LogFile => "OnBakeStarted";
public enum Stages
{
OnBakeStarted,
PrepareWorldSubdivision,
EnsurePerSceneDataInOpenScenes,
FindWorldBounds,
PlaceProbes,
BakeBricks,
ApplySubdivisionResults,
None
}
static Stages currentStage = Stages.None;
public BakingSetupProfiling(Stages stage) : base(stage, ref currentStage) { }
public override Stages GetLastStep() => Stages.None;
public static void GetProgressRange(out float progress0, out float progress1) { float s = 1 / (float)Stages.None; progress0 = (float)currentStage * s; progress1 = progress0 + s; }
public void Dispose() { OnDispose(ref currentStage); }
}
internal class BakingCompleteProfiling : BakingProfiling<BakingCompleteProfiling.Stages>, IDisposable
{
//protected override string LogFile => "OnAdditionalProbesBakeCompleted";
public enum Stages
{
FinalizingBake,
WriteBakedData,
PerformDilation,
None
}
static Stages currentStage = Stages.None;
public BakingCompleteProfiling(Stages stage) : base(stage, ref currentStage) { }
public override Stages GetLastStep() => Stages.None;
public static void GetProgressRange(out float progress0, out float progress1) { float s = 1 / (float)Stages.None; progress0 = (float)currentStage * s; progress1 = progress0 + s; }
public void Dispose() { OnDispose(ref currentStage); }
}
struct BakeData
{
// Inputs
public BakeJob[] jobs;
public int probeCount;
public int reflectionProbeCount;
public NativeArray<int> positionRemap;
public NativeArray<Vector3> originalPositions;
public NativeArray<Vector3> sortedPositions;
public InputExtraction.BakeInput bakeInput;
// Workers
public Thread bakingThread;
public VirtualOffsetBaker virtualOffsetJob;
public SkyOcclusionBaker skyOcclusionJob;
public LightingBaker lightingJob;
public RenderingLayerBaker layerMaskJob;
public int cellIndex;
public Thread fixSeamsThread;
public bool doneFixingSeams;
// Progress reporting
public BakingStep step;
public ulong stepCount;
// Cancellation
public bool failed;
[Flags]
enum BakeJobRequests
{
MAIN_REQUEST = 1,
TOUCHUP_REQUESTS = 2,
ADDITIONAL_REQUEST = 4
}
internal static void InitVirtualOffsetJob(IntPtr pVirtualOffsetsBuffer, ref bool bakeVirtualOffsets)
{
bool usingVirtualOffset = m_BakingSet.settings.virtualOffsetSettings.useVirtualOffset;
if (!usingVirtualOffset)
{
bakeVirtualOffsets = false;
Debug.Assert(s_BakeData.virtualOffsetJob == null);
return;
}
var virtualOffsets = new VirtualOffsets(pVirtualOffsetsBuffer);
s_BakeData.virtualOffsetJob = virtualOffsetOverride ?? new DefaultVirtualOffset();
s_BakeData.virtualOffsetJob.Initialize(m_BakingSet,
s_BakeData.sortedPositions.GetSubArray(0, s_BakeData.probeCount));
s_BakeData.VirtualOffsets = virtualOffsets; // This is an internal secret, it is only used by our own virtual offsets baker
bakeVirtualOffsets = true;
}
VirtualOffsets VirtualOffsets { get; set; }
internal static void UpdateVirtualOffsetJob(ref float progress, ref bool done)
{
if (s_BakeData.virtualOffsetJob == null)
{
done = true;
progress = 1.0f;
return;
}
if (!s_BakeData.virtualOffsetJob.Step())
{
s_BakeData.failed = true;
done = true;
progress = 1.0f;
return;
}
if (s_BakeData.virtualOffsetJob.currentStep >= s_BakeData.virtualOffsetJob.stepCount)
{
done = true;
progress = 1.0f;
if (s_BakeData.virtualOffsetJob.offsets.IsCreated)
{
s_BakeData.ApplyVirtualOffset();
s_BakeData.VirtualOffsets.SetVirtualOffsets(s_BakeData.virtualOffsetJob.offsets.ToArray());
}
s_BakeData.VirtualOffsets?.Dispose(); // Disposes our own wrapper, we don't own the underlying data so it will not be disposed
s_BakeData.VirtualOffsets = null;
}
else
progress = s_BakeData.virtualOffsetJob.currentStep == 0
? 0
: (float)s_BakeData.virtualOffsetJob.currentStep / s_BakeData.virtualOffsetJob.stepCount;
}
public void Init(ProbeVolumeBakingSet bakingSet, NativeList<Vector3> probePositions, List<Vector3> requests, BakeType bakeType)
{
probeCount = probePositions.Length;
reflectionProbeCount = requests.Count;
var probeJobRequests = BakeJobRequests.MAIN_REQUEST | BakeJobRequests.TOUCHUP_REQUESTS;
if (requests.Count > 0)
probeJobRequests |= BakeJobRequests.ADDITIONAL_REQUEST;
jobs = CreateBakingJobs(bakingSet, probeJobRequests);
originalPositions = probePositions.ToArray(Allocator.Persistent);
SortPositions(probePositions, requests);
skyOcclusionJob = skyOcclusionOverride ?? new DefaultSkyOcclusion();
skyOcclusionJob.Initialize(bakingSet, sortedPositions.GetSubArray(0, probeCount));
if (skyOcclusionJob is DefaultSkyOcclusion defaultSOJob)
defaultSOJob.jobs = jobs;
layerMaskJob = renderingLayerOverride ?? new DefaultRenderingLayer();
layerMaskJob.Initialize(bakingSet, sortedPositions.GetSubArray(0, probeCount));
lightingJob = lightingOverride ?? new DefaultLightTransport();
lightingJob.Initialize(ProbeVolumeLightingTab.GetLightingSettings().mixedBakeMode != MixedLightingMode.IndirectOnly, sortedPositions, layerMaskJob.renderingLayerMasks);
if (lightingJob is DefaultLightTransport defaultLightTransport)
defaultLightTransport.bakeType = bakeType;
cellIndex = 0;
LightingBaker.cancel = false;
step = BakingStep.LaunchThread;
stepCount = skyOcclusionJob.stepCount + lightingJob.stepCount;
}
public void InitAdditionalRequests(NativeList<Vector3> probePositions, List<Vector3> requests, BakeType bakeType)
{
probeCount = probePositions.Length;
reflectionProbeCount = requests.Count;
jobs = CreateAdditionalBakingJobs();
originalPositions = probePositions.ToArray(Allocator.Persistent);
SortPositions(probePositions, requests);
lightingJob = lightingOverride ?? new DefaultLightTransport();
using var layerMask = new NativeArray<uint>();
lightingJob.Initialize(ProbeVolumeLightingTab.GetLightingSettings().mixedBakeMode != MixedLightingMode.IndirectOnly, sortedPositions, layerMask);
if (lightingJob is DefaultLightTransport defaultLightTransport)
defaultLightTransport.bakeType = bakeType;
cellIndex = 0;
LightingBaker.cancel = false;
step = BakingStep.LaunchThread;
stepCount = lightingJob.stepCount;
}
public void InitLightingJob(ProbeVolumeBakingSet bakingSet, ProbeAdjustmentVolume touchup, NativeList<Vector3> probePositions, BakeType bakeType)
{
probeCount = probePositions.Length;
s_AdjustmentVolumes = new TouchupVolumeWithBoundsList();
touchup.GetOBBandAABB(out var obb, out var aabb);
s_AdjustmentVolumes.Add((obb, aabb, touchup));
touchup.skyDirection.Normalize();
var probeJobRequests = BakeJobRequests.TOUCHUP_REQUESTS;
if (touchup.mode != ProbeAdjustmentVolume.Mode.OverrideSampleCount)
{
// Other touchup volumes don't need a job of their own but they do need a main request job
probeJobRequests |= BakeJobRequests.MAIN_REQUEST;
}
jobs = CreateBakingJobs(bakingSet, probeJobRequests);
SortPositions(probePositions, new List<Vector3>());
lightingJob = lightingOverride ?? new DefaultLightTransport();
lightingJob.Initialize(ProbeVolumeLightingTab.GetLightingSettings().mixedBakeMode != MixedLightingMode.IndirectOnly, sortedPositions);
if (lightingJob is DefaultLightTransport defaultLightTransport)
defaultLightTransport.bakeType = bakeType;
LightingBaker.cancel = false;
}
public void ExecuteLightingAsync()
{
bakingThread = new Thread(() => {
var job = s_BakeData.lightingJob;
while (job.currentStep < job.stepCount)
{
if (!job.Step())
{
s_BakeData.failed = true;
return;
}
if (LightingBaker.cancel)
break;
}
});
bakingThread.Start();
}
static BakeJob[] CreateBakingJobs(ProbeVolumeBakingSet bakingSet, BakeJobRequests bakeJobRequests)
{
// Build the list of adjustment volumes affecting sample count
var touchupVolumesAndBounds = new TouchupVolumeWithBoundsList();
if (bakeJobRequests.HasFlag(BakeJobRequests.TOUCHUP_REQUESTS))
{
// This is slow, but we should have very little amount of touchup volumes.
foreach (var adjustment in s_AdjustmentVolumes)
{
if (adjustment.volume.mode == ProbeAdjustmentVolume.Mode.OverrideSampleCount)
{
touchupVolumesAndBounds.Add(adjustment);
}
}
// Sort by volume to give priority to smaller volumes
touchupVolumesAndBounds.Sort((a, b) => (a.volume.ComputeVolume(a.obb).CompareTo(b.volume.ComputeVolume(b.obb))));
}
var lightingSettings = ProbeVolumeLightingTab.GetLightingSettings();
bool skyOcclusion = bakingSet.skyOcclusion;
var jobs = new List<BakeJob>();
if (bakeJobRequests.HasFlag(BakeJobRequests.TOUCHUP_REQUESTS))
{
foreach (var touchupVolume in touchupVolumesAndBounds)
{
BakeJob job = new BakeJob();
job.Create(lightingSettings, skyOcclusion, touchupVolume);
jobs.Add(job);
}
}
if (bakeJobRequests.HasFlag(BakeJobRequests.MAIN_REQUEST))
{
BakeJob job = new BakeJob();
job.Create(bakingSet, lightingSettings, skyOcclusion);
jobs.Add(job);
}
if (bakeJobRequests.HasFlag(BakeJobRequests.ADDITIONAL_REQUEST))
{
BakeJob job = new BakeJob();
job.Create(bakingSet, lightingSettings, false);
jobs.Add(job);
}
return jobs.ToArray();
}
static BakeJob[] CreateAdditionalBakingJobs()
{
// Build the list of adjustment volumes affecting sample count
var touchupVolumesAndBounds = new TouchupVolumeWithBoundsList();
{
// This is slow, but we should have very little amount of touchup volumes.
foreach (var adjustment in s_AdjustmentVolumes)
{
if (adjustment.volume.mode == ProbeAdjustmentVolume.Mode.OverrideSampleCount)
touchupVolumesAndBounds.Add(adjustment);
}
// Sort by volume to give priority to smaller volumes
touchupVolumesAndBounds.Sort((a, b) => (a.volume.ComputeVolume(a.obb).CompareTo(b.volume.ComputeVolume(b.obb))));
}
var lightingSettings = ProbeVolumeLightingTab.GetLightingSettings();
bool skyOcclusion = false;
var jobs = new BakeJob[touchupVolumesAndBounds.Count + 1];
for (int i = 0; i < touchupVolumesAndBounds.Count; i++)
jobs[i].Create(lightingSettings, skyOcclusion, touchupVolumesAndBounds[i]);
jobs[touchupVolumesAndBounds.Count].Create(null, lightingSettings, false);
return jobs;
}
// Place positions contiguously for each bake job in a single array, with reflection probes at the end
public void SortPositions(NativeList<Vector3> probePositions, List<Vector3> additionalRequests)
{
positionRemap = new NativeArray<int>(probePositions.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
sortedPositions = new NativeArray<Vector3>(probePositions.Length + additionalRequests.Count, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
int regularJobCount = additionalRequests.Count != 0 ? jobs.Length - 1 : jobs.Length;
// Place each probe in the correct job
int[] jobSize = new int[regularJobCount];
for (int i = 0; i < probePositions.Length; i++)
{
// Last regular job (so before reflection probes if they exist) is the default one
// In case we don't match any touchup, we should be placed in this one
int jobIndex = 0;
for (; jobIndex < regularJobCount - 1; jobIndex++)
{
if (jobs[jobIndex].Contains(probePositions[i]))
break;
}
positionRemap[i] = jobIndex;
jobSize[jobIndex]++;
}
// Compute the size and offset of each job in the sorted array
int currentOffset = 0;
for (int i = 0; i < regularJobCount; i++)
{
ref var job = ref jobs[i];
job.startOffset = currentOffset;
job.probeCount = jobSize[i];
currentOffset += job.probeCount;
jobSize[i] = 0;
}
Debug.Assert(currentOffset == probePositions.Length);
// Sort position and store remapping
for (int i = 0; i < probePositions.Length; i++)
{
int jobIndex = positionRemap[i];
int newPos = jobs[jobIndex].startOffset + jobSize[jobIndex]++;
positionRemap[i] = newPos;
sortedPositions[newPos] = probePositions[i];
}
// Place reflection probe positions at the end of the array
if (additionalRequests.Count != 0)
{
ref var requestJob = ref jobs[jobs.Length - 1];
requestJob.startOffset = currentOffset;
requestJob.probeCount = additionalRequests.Count;
for (int i = 0; i < additionalRequests.Count; i++)
sortedPositions[currentOffset++] = additionalRequests[i];
Debug.Assert(currentOffset == sortedPositions.Length);
}
}
public void ApplyVirtualOffset()
{
NativeArray<Vector3> offsets = virtualOffsetJob.offsets;
for (int i = 0; i < offsets.Length; i++)
sortedPositions[i] += offsets[i];
}
public bool Done()
{
ulong currentStep = s_BakeData.lightingJob.currentStep + s_BakeData.skyOcclusionJob.currentStep;
return currentStep >= s_BakeData.stepCount && s_BakeData.step == BakingStep.Last;
}
public void CleanUp()
{
if (failed)
Debug.LogError("Probe Volume Baking failed.");
if (jobs == null)
return;
foreach (var job in jobs)
job.Dispose();
positionRemap.Dispose();
originalPositions.Dispose();
sortedPositions.Dispose();
skyOcclusionJob?.encodedDirections.Dispose();
virtualOffsetJob?.Dispose();
virtualOffsetJob = null;
skyOcclusionJob?.Dispose();
lightingJob.Dispose();
layerMaskJob?.Dispose();
// clear references to managed data
this = default;
}
public void CleanUpLightingJob()
{
if (failed)
Debug.LogError("Probe Volume Baking failed.");
lightingJob.Dispose();
// clear references to managed data
this = default;
}
}
static bool m_IsInit = false;
static BakingBatch m_BakingBatch;
static ProbeVolumeBakingSetWeakReference m_BakingSetReference = new();
static ProbeVolumeBakingSet m_BakingSet
{
get => m_BakingSetReference.Get();
set => m_BakingSetReference.Set(value);
}
static TouchupVolumeWithBoundsList s_AdjustmentVolumes;
static Bounds globalBounds = new Bounds();
static Vector3Int minCellPosition = Vector3Int.one * int.MaxValue;
static Vector3Int maxCellPosition = Vector3Int.one * int.MinValue;
static Vector3Int cellCount = Vector3Int.zero;
static int pvHashesAtBakeStart = -1;
static APVRTContext s_TracingContext;
static BakeData s_BakeData;
static Dictionary<int, BakingCell> m_BakedCells = new Dictionary<int, BakingCell>();
internal static HashSet<string> partialBakeSceneList = null;
internal static bool isBakingSceneSubset => partialBakeSceneList != null;
internal static bool isFreezingPlacement = false;
static SphericalHarmonicsL2 s_BlackSH;
static bool s_BlackSHInitialized = false;
static SphericalHarmonicsL2 GetBlackSH()
{
if (!s_BlackSHInitialized)
{
// Init SH with values that will resolve to black
s_BlackSH = new SphericalHarmonicsL2();
for (int channel = 0; channel < 3; ++channel)
{
s_BlackSH[channel, 0] = 0.0f;
for (int coeff = 1; coeff < 9; ++coeff)
s_BlackSH[channel, coeff] = 0.5f;
}
}
return s_BlackSH;
}
static AdaptiveProbeVolumes()
{
Init();
}
static internal void Init()
{
if (!m_IsInit)
{
m_IsInit = true;
Lightmapping.lightingDataCleared += OnLightingDataCleared;
Lightmapping.bakeStarted += OnBakeStarted;
Lightmapping.bakeCancelled += OnBakeCancelled;
Lightmapping.inputExtraction += OnInputExtraction;
}
}
internal static void CleanUp()
{
s_TracingContext.Dispose();
}
static void OnLightingDataCleared()
{
if (ProbeReferenceVolume.instance == null)
return;
if (!ProbeReferenceVolume.instance.isInitialized || !ProbeReferenceVolume.instance.enabledBySRP)
return;
Clear();
}
static internal void Clear()
{
var activeSet = ProbeVolumeBakingSet.GetBakingSetForScene(SceneManager.GetActiveScene());
foreach (var data in ProbeReferenceVolume.instance.perSceneDataList)
data.Clear();
ProbeReferenceVolume.instance.Clear();
if (activeSet != null)
activeSet.Clear();
#pragma warning disable CS0618 // Type or member is obsolete
var probeVolumes = GameObject.FindObjectsByType<ProbeVolume>(FindObjectsSortMode.InstanceID);
#pragma warning restore CS0618 // Type or member is obsolete
foreach (var probeVolume in probeVolumes)
probeVolume.OnLightingDataAssetCleared();
}
static bool SetBakingContext(List<ProbeVolumePerSceneData> perSceneData)
{
var prv = ProbeReferenceVolume.instance;
bool isBakingSingleScene = false;
for (int i = 0; i < perSceneData.Count; ++i)
{
var data = perSceneData[i];
var scene = data.gameObject.scene;
var bakingSet = ProbeVolumeBakingSet.GetBakingSetForScene(scene);
if (bakingSet != null && bakingSet.singleSceneMode)
{
isBakingSingleScene = true;
break;
}
}
// We need to make sure all scenes we are baking are from the same baking set.
// TODO: This should be ensured by the controlling panel, until we have that we need to assert.
for (int i = 0; i < perSceneData.Count; ++i)
{
var data = perSceneData[i];
var sceneGUID = data.sceneGUID;
var bakingSet = ProbeVolumeBakingSet.GetBakingSetForScene(sceneGUID);
if (bakingSet == null)
{
if (isBakingSingleScene)
continue;
var sceneName = data.gameObject.scene.name;
Debug.LogError($"Scene '{sceneName}' does not belong to any Baking Set. Please add it to a Baking Set in the Adaptive Probe Volumes tab of the Lighting Window.");
return false;
}
bakingSet.SetActiveScenario(bakingSet.lightingScenario, verbose: false); // Ensure we are not blending any other scenario.
bakingSet.BlendLightingScenario(null, 0.0f);
if (i == 0)
m_BakingSet = bakingSet;
else if (!m_BakingSet.IsEquivalent(bakingSet))
return false;
}
return true;
}
static bool EnsurePerSceneDataInOpenScenes()
{
var prv = ProbeReferenceVolume.instance;
var activeScene = SceneManager.GetActiveScene();
var activeSet = ProbeVolumeBakingSet.GetBakingSetForScene(activeScene);
if (activeSet == null && ProbeVolumeBakingSet.SceneHasProbeVolumes(ProbeReferenceVolume.GetSceneGUID(activeScene)))
{
Debug.LogError($"Active scene at {activeScene.path} is not part of any baking set.");
return false;
}
// We assume that all the per scene data for all the scenes in the set have been set with the scene been saved at least once. However we also update the scenes that are currently loaded anyway for security.
// and to have a new trigger to update the bounds we have.
int openedScenesCount = SceneManager.sceneCount;
for (int i = 0; i < openedScenesCount; ++i)
{
var scene = SceneManager.GetSceneAt(i);
if (!scene.isLoaded)
continue;
ProbeVolumeBakingSet.OnSceneSaving(scene); // We need to perform the same actions we do when the scene is saved.
var sceneBakingSet = ProbeVolumeBakingSet.GetBakingSetForScene(scene);