-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathLightBakerStrangler.cs
More file actions
1623 lines (1412 loc) · 90.6 KB
/
LightBakerStrangler.cs
File metadata and controls
1623 lines (1412 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.Collections.Generic;
using System.IO;
using System;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.LightTransport;
using UnityEngine.PathTracing.Integration;
using UnityEngine.Rendering;
using UnityEngine.Assertions;
using UnityEngine.PathTracing.Core;
using UnityEngine.PathTracing.Lightmapping;
using UnityEngine.Rendering.UnifiedRayTracing;
using Unity.Collections.LowLevel.Unsafe;
using System.Runtime.InteropServices;
using UnityEditor.PathTracing.Debugging;
namespace UnityEditor.PathTracing.LightBakerBridge
{
using static BakeLightmapDriver;
using InstanceHandle = Handle<World.InstanceKey>;
internal static class WorldHelpers
{
static void MultiValueDictAdd<TKey, TValue>(Dictionary<TKey, List<TValue>> dict, TKey key, TValue value)
{
List<TValue> values = null;
if (dict.TryGetValue(key, out values))
{
values.Add(value);
}
else
{
values = new List<TValue> { value };
dict.Add(key, values);
}
}
internal static void AddContributingInstancesToWorld(World world, in FatInstance[] fatInstances, out Dictionary<int, List<LodInstanceBuildData>> lodInstances, out Dictionary<Int32, List<ContributorLodInfo>> lodgroupToContributorInstances)
{
lodInstances = new();
lodgroupToContributorInstances = new();
// Add instances to world
foreach (var fatInstance in fatInstances)
{
if (fatInstance.LodIdentifier.IsValid() && !fatInstance.LodIdentifier.IsContributor())
{
WorldHelpers.MultiValueDictAdd(lodInstances, fatInstance.LodIdentifier.LodGroup, new LodInstanceBuildData
{
LodMask = fatInstance.LodIdentifier.LodMask,
Mesh = fatInstance.Mesh,
Materials = fatInstance.Materials,
Masks = fatInstance.SubMeshMasks,
LocalToWorldMatrix = fatInstance.LocalToWorldMatrix,
Bounds = fatInstance.Bounds,
IsStatic = fatInstance.IsStatic,
Filter = fatInstance.Filter
});
continue;
}
var instanceHandle = world.AddInstance(
fatInstance.Mesh,
fatInstance.Materials,
fatInstance.SubMeshMasks,
fatInstance.RenderingObjectLayer,
fatInstance.LocalToWorldMatrix,
fatInstance.Bounds,
fatInstance.IsStatic,
fatInstance.Filter,
fatInstance.EnableEmissiveSampling);
if (fatInstance.LodIdentifier.IsValid() && fatInstance.LodIdentifier.IsContributor())
WorldHelpers.MultiValueDictAdd(lodgroupToContributorInstances, fatInstance.LodIdentifier.LodGroup, new ContributorLodInfo
{
LodMask = fatInstance.LodIdentifier.LodMask,
InstanceHandle = instanceHandle,
Masks = fatInstance.SubMeshMasks
});
}
}
}
internal class LightBakerStrangler
{
internal enum Result
{
Success,
InitializeFailure,
CreateDirectoryFailure,
CreateLightmapFailure,
AddResourcesToCacheFailure,
InitializeExpandedBufferFailure,
WriteToDiskFailure,
Cancelled
};
// File layout matches WriteInterleavedSHArrayToFile.
private static bool SaveProbesToFileInterleaved(string filename, NativeArray<SphericalHarmonicsL2> shArray)
{
Debug.Assert(filename is not null, "Filename is null");
string path = Path.GetDirectoryName(filename);
Debug.Assert(path is not null, "path is null");
var info = Directory.CreateDirectory(path);
if (info.Exists == false)
return false;
// Write the number of probes to file as Int64.
Int64 arraySize = shArray.Length;
byte[] probeCountBytes = BitConverter.GetBytes(arraySize);
List<byte> byteList = new();
byteList.AddRange(probeCountBytes);
// Write all probe coefficients, ordered by coefficient.
const int sphericalHarmonicsL2CoeffCount = 9;
byte[] floatPaddingBytes = BitConverter.GetBytes(0.0f);
for (int coefficient = 0; coefficient < sphericalHarmonicsL2CoeffCount; ++coefficient)
{
for (int i = 0; i < shArray.Length; i++)
{
SphericalHarmonicsL2 sh = shArray[i];
for (int rgb = 0; rgb < 3; rgb++)
{
float coefficientValue = sh[rgb, coefficient];
byte[] floatBytes = BitConverter.GetBytes(coefficientValue);
byteList.AddRange(floatBytes);
}
byteList.AddRange(floatPaddingBytes); // pad to match Vector4 size.
}
}
File.WriteAllBytes(filename, byteList.ToArray());
return true;
}
private static bool SaveArrayToFile<T>(string filename, int count, T[] array)
where T : unmanaged
{
// Create output directory if it doesn't exist already.
Debug.Assert(filename is not null, "Filename is null");
string path = Path.GetDirectoryName(filename);
Debug.Assert(path is not null, "path is null");
var info = Directory.CreateDirectory(path);
if (info.Exists == false)
return false;
// Prepare output buffer.
int numElementBytes = array.Length * UnsafeUtility.SizeOf<T>();
byte[] bytes = new byte[sizeof(Int64) + numElementBytes]; // + sizeof(Int64) for the count.
// Write the number of elements to file as Int64.
Int64 arraySize = count;
byte[] countBytes = BitConverter.GetBytes(arraySize);
Buffer.BlockCopy(countBytes, 0, bytes, 0, countBytes.Length);
// Write contents of array to file. This is safe because of the unmanaged constraint on T.
unsafe
{
fixed (T* arrayPtr = array)
fixed (byte* bytesPtr = bytes)
{
UnsafeUtility.MemCpy(bytesPtr + sizeof(Int64), arrayPtr, numElementBytes);
}
}
File.WriteAllBytes(filename, bytes);
return true;
}
private static HashSet<LightmapRequestOutputType> BitfieldToList(int bitfield)
{
var outputTypes = new HashSet<LightmapRequestOutputType>();
// Loop through the enum values
foreach (LightmapRequestOutputType channel in Enum.GetValues(typeof(LightmapRequestOutputType)))
{
// Check if the bitfield has the current value set
if ((bitfield & (int) channel) == 0)
continue;
// Add the value to the list
if (channel != LightmapRequestOutputType.All)
outputTypes.Add(channel);
}
return outputTypes;
}
private static bool LightmapRequestOutputTypeToIntegratedOutputType(LightmapRequestOutputType type, out IntegratedOutputType integratedOutputType)
{
integratedOutputType = IntegratedOutputType.AO;
switch (type)
{
case LightmapRequestOutputType.IrradianceIndirect:
integratedOutputType = IntegratedOutputType.Indirect;
return true;
case LightmapRequestOutputType.IrradianceDirect:
integratedOutputType = IntegratedOutputType.Direct;
return true;
case LightmapRequestOutputType.Occupancy: // Occupancy do not need accumulation
return false;
case LightmapRequestOutputType.Validity:
integratedOutputType = IntegratedOutputType.Validity;
return true;
case LightmapRequestOutputType.DirectionalityIndirect:
integratedOutputType = IntegratedOutputType.DirectionalityIndirect;
return true;
case LightmapRequestOutputType.DirectionalityDirect:
integratedOutputType = IntegratedOutputType.DirectionalityDirect;
return true;
case LightmapRequestOutputType.AmbientOcclusion:
integratedOutputType = IntegratedOutputType.AO;
return true;
case LightmapRequestOutputType.Shadowmask:
integratedOutputType = IntegratedOutputType.ShadowMask;
return true;
// These types do not need accumulation:
case LightmapRequestOutputType.Normal:
case LightmapRequestOutputType.ChartIndex:
case LightmapRequestOutputType.OverlapPixelIndex:
case LightmapRequestOutputType.IrradianceEnvironment:
return false;
}
Debug.Assert(false, $"Error unknown LightmapRequestOutputType {type}.");
return false;
}
// We can ignore the G-Buffer data part of atlassing, we are using stochastic sampling instead.
internal static LightmapDesc[] PopulateLightmapDescsFromAtlassing(in PVRAtlassingData atlassing, in FatInstance[] fatInstances)
{
int atlasCount = atlassing.m_AtlasHashToGBufferHash.Count;
var lightmapDescs = new LightmapDesc[atlasCount];
foreach (var atlasIdToAtlasHash in atlassing.m_AtlasIdToAtlasHash)
{
int atlasId = atlasIdToAtlasHash.m_AtlasId;
// Get the array of object ID hashes for the given atlas.
bool found = atlassing.m_AtlasHashToObjectIDHashes.TryGetValue(
atlasIdToAtlasHash.m_AtlasHash, out IndexHash128[] objectIDHashes);
Debug.Assert(found, $"Couldn't find object ID hashes for atlas {atlasIdToAtlasHash.m_AtlasHash}.");
// Get the GBuffer data for the given atlas, so we can use it to find instance data like IDs and transforms.
found = atlassing.m_AtlasHashToGBufferHash.TryGetValue(
atlasIdToAtlasHash.m_AtlasHash, out _);
if (found == false)
continue; // Skip atlasses without GBuffers, they are used for SSD objects.
uint lightmapResolution = (uint)atlassing.m_AtlasSizes[atlasId].width;
Debug.Assert(lightmapResolution == atlassing.m_AtlasSizes[atlasId].height,
"The following code assumes that we always have square lightmaps.");
uint antiAliasingSampleCount = (uint)((int)atlasIdToAtlasHash.m_BakeParameters.supersamplingMultiplier * (int)atlasIdToAtlasHash.m_BakeParameters.supersamplingMultiplier);
var lightmapDesc = new LightmapDesc
{
Resolution = lightmapResolution,
PushOff = atlasIdToAtlasHash.m_BakeParameters.pushOff
};
int instanceCount = objectIDHashes.Length;
var bakeInstances = new BakeInstance[instanceCount];
int instanceCounter = 0;
foreach (var instanceHash in objectIDHashes)
{
// Get the AtlassedInstanceData for the instance.
found = atlassing.m_InstanceAtlassingData.TryGetValue(instanceHash,
out AtlassedInstanceData atlassedInstanceData);
Debug.Assert(found, $"Didn't find AtlassedInstanceData for instance {instanceHash}.");
Debug.Assert(atlassedInstanceData.m_AtlasId == atlasId, "Atlas ID mismatch.");
// Get the instance from bakeInput and create a Mesh.
uint bakeInputInstanceIndex = (uint)instanceHash.Index;
ref readonly FatInstance fatInstance = ref fatInstances[bakeInputInstanceIndex];
LightmapIntegrationHelpers.ComputeOccupiedTexelRegionForInstance(
lightmapResolution, lightmapResolution, atlassedInstanceData.m_LightmapST, fatInstance.UVBoundsSize, fatInstance.UVBoundsOffset,
out Vector4 normalizedOccupiedST, out Vector2Int occupiedTexelSize, out Vector2Int occupiedTexelOffset);
bakeInstances[instanceCounter].Build(
fatInstance.Mesh,
normalizedOccupiedST,
atlassedInstanceData.m_LightmapST,
occupiedTexelSize,
occupiedTexelOffset,
fatInstance.LocalToWorldMatrix,
fatInstance.ReceiveShadows,
fatInstance.LodIdentifier,
bakeInputInstanceIndex);
++instanceCounter;
}
lightmapDesc.BakeInstances = bakeInstances;
lightmapDescs[atlasId] = lightmapDesc;
}
return lightmapDescs;
}
private static void MakeOutputFolderPathsFullyQualified(ProbeRequest[] probeRequestsToFixUp, string bakeOutputFolderPath)
{
for (int i = 0; i < probeRequestsToFixUp.Length; i++)
{
ref ProbeRequest request = ref probeRequestsToFixUp[i];
request.outputFolderPath = Path.GetFullPath(request.outputFolderPath, bakeOutputFolderPath);
}
}
private static void MakeOutputFolderPathsFullyQualified(LightmapRequest[] requestsToFixUp, string bakeOutputFolderPath)
{
for (int i = 0; i < requestsToFixUp.Length; i++)
{
ref LightmapRequest request = ref requestsToFixUp[i];
request.outputFolderPath = Path.GetFullPath(request.outputFolderPath, bakeOutputFolderPath);
}
}
internal static bool Bake(string bakeInputPath, string lightmapRequestsPath, string lightProbeRequestsPath, string bakeOutputFolderPath, BakeProgressState progressState)
{
using (new BakeProfilingScope())
{
// Read BakeInput and requests from LightBaker
if (!BakeInputSerialization.Deserialize(bakeInputPath, out BakeInput bakeInput))
return false;
if (!BakeInputSerialization.Deserialize(lightmapRequestsPath, out LightmapRequestData lightmapRequestData))
return false;
if (!BakeInputSerialization.Deserialize(lightProbeRequestsPath, out ProbeRequestData probeRequestData))
return false;
// Change output folder paths from relative to absolute
MakeOutputFolderPathsFullyQualified(probeRequestData.requests, bakeOutputFolderPath);
MakeOutputFolderPathsFullyQualified(lightmapRequestData.requests, bakeOutputFolderPath);
IntegrationSettings integrationSettings = GetIntegrationSettings(bakeInput);
// Setup ray tracing context
RayTracingBackend backend = integrationSettings.Backend;
Debug.Assert(RayTracingContext.IsBackendSupported(backend), $"Backend {backend} is not supported!");
RayTracingResources rayTracingResources = new RayTracingResources();
rayTracingResources.Load();
using var rayTracingContext = new RayTracingContext(backend, rayTracingResources);
// Setup device context
using UnityComputeDeviceContext deviceContext = new();
bool initOk = deviceContext.Initialize();
Assert.IsTrue(initOk, "Failed to initialize DeviceContext.");
// Create and init world
var worldResources = new WorldResourceSet();
worldResources.LoadFromAssetDatabase();
using UnityComputeWorld world = new();
world.Init(rayTracingContext, worldResources);
using var samplingResources = new UnityEngine.Rendering.Sampling.SamplingResources();
samplingResources.Load((uint)UnityEngine.Rendering.Sampling.SamplingResources.ResourceType.All);
// Deserialize BakeInput, inject data into world
const bool useLegacyBakingBehavior = true;
const bool autoEstimateLUTRange = true;
BakeInputToWorldConversion.InjectBakeInputData(world.PathTracingWorld, autoEstimateLUTRange, in bakeInput,
out Bounds sceneBounds, out world.Meshes, out FatInstance[] fatInstances, out world.LightHandles,
world.TemporaryObjects, UnityComputeWorld.RenderingObjectLayer);
// Add instances to world
WorldHelpers.AddContributingInstancesToWorld(world.PathTracingWorld, in fatInstances, out var lodInstances, out var lodgroupToContributorInstances);
// Build world with extracted data
const bool emissiveSampling = true;
world.PathTracingWorld.Build(sceneBounds, deviceContext.GetCommandBuffer(), ref world.ScratchBuffer, samplingResources, emissiveSampling, 1024);
LightmapBakeSettings lightmapBakeSettings = GetLightmapBakeSettings(bakeInput);
// Build array of lightmap descriptors based on the atlassing data and instances.
LightmapDesc[] lightmapDescriptors = PopulateLightmapDescsFromAtlassing(in lightmapRequestData.atlassing, in fatInstances);
SortInstancesByMeshAndResolution(lightmapDescriptors);
ulong probeWorkSteps = CalculateWorkStepsForProbeRequests(in bakeInput, in probeRequestData);
ulong lightmapWorkSteps = CalculateWorkStepsForLightmapRequests(in lightmapRequestData, lightmapDescriptors, lightmapBakeSettings);
progressState.SetTotalWorkSteps(probeWorkSteps + lightmapWorkSteps);
if (!ExecuteProbeRequests(in bakeInput, in probeRequestData, deviceContext, useLegacyBakingBehavior, world, progressState, samplingResources))
return false;
if (lightmapRequestData.requests.Length <= 0)
return true;
// Populate resources structure
LightmapResourceLibrary resources = new();
resources.Load(world.RayTracingContext);
if (ExecuteLightmapRequests(in lightmapRequestData, deviceContext, world, in fatInstances, in lodInstances, in lodgroupToContributorInstances, integrationSettings, useLegacyBakingBehavior, resources, progressState, lightmapDescriptors, lightmapBakeSettings, samplingResources) != Result.Success)
return false;
CoreUtils.Destroy(resources.UVFallbackBufferGenerationMaterial);
return true;
}
}
internal static ulong CalculateWorkStepsForProbeRequests(in BakeInput bakeInput, in ProbeRequestData probeRequestData)
{
ulong calculatedWorkSteps = 0;
foreach (ProbeRequest probeRequest in probeRequestData.requests)
{
(uint directSampleCount, uint effectiveIndirectSampleCount) = GetProbeSampleCounts(probeRequest.sampleCount);
calculatedWorkSteps += CalculateProbeWorkSteps(probeRequest.count, probeRequest.outputTypeMask,
directSampleCount, effectiveIndirectSampleCount,
bakeInput.lightingSettings.mixedLightingMode != MixedLightingMode.IndirectOnly,
probeRequest.maxBounces);
}
return calculatedWorkSteps;
}
private static ulong CalculateProbeWorkSteps(ulong count, ProbeRequestOutputType outputTypeMask, uint directSampleCount, uint effectiveIndirectSampleCount, bool usesProbeOcclusion, uint bounceCount)
{
ulong workSteps = 0;
if (outputTypeMask.HasFlag(ProbeRequestOutputType.RadianceIndirect))
workSteps += ProbeIntegrator.CalculateWorkSteps(count, effectiveIndirectSampleCount, bounceCount);
if (outputTypeMask.HasFlag(ProbeRequestOutputType.RadianceDirect))
workSteps += ProbeIntegrator.CalculateWorkSteps(count, directSampleCount, 0);
if (outputTypeMask.HasFlag(ProbeRequestOutputType.Validity))
workSteps += ProbeIntegrator.CalculateWorkSteps(count, effectiveIndirectSampleCount, 0);
if (outputTypeMask.HasFlag(ProbeRequestOutputType.LightProbeOcclusion) && usesProbeOcclusion)
workSteps += ProbeIntegrator.CalculateWorkSteps(count, effectiveIndirectSampleCount, 0);
return workSteps;
}
internal static ulong CalculateWorkStepsForLightmapRequests(in LightmapRequestData lightmapRequestData, LightmapDesc[] lightmapDescriptors, LightmapBakeSettings lightmapBakeSettings)
{
ulong calculatedWorkSteps = 0;
foreach (LightmapRequest r in lightmapRequestData.requests)
{
ref readonly var request = ref r;
if (request.lightmapCount == 0)
continue;
for (int lightmapIndex = 0; lightmapIndex < request.lightmapCount; lightmapIndex++)
{
LightmapDesc currentLightmapDesc = lightmapDescriptors[lightmapIndex];
Dictionary<IntegratedOutputType, RequestedSubOutput> requestedLightmapTypes = GetRequestedIntegratedOutputTypes(request);
foreach (IntegratedOutputType lightmapType in requestedLightmapTypes.Keys)
{
uint sampleCount = lightmapBakeSettings.GetSampleCount(lightmapType);
foreach (BakeInstance bakeInstance in currentLightmapDesc.BakeInstances)
{
uint instanceWidth = (uint)bakeInstance.TexelSize.x;
uint instanceHeight = (uint)bakeInstance.TexelSize.y;
calculatedWorkSteps += CalculateIntegratedLightmapWorkSteps(sampleCount, instanceWidth * instanceHeight, lightmapType, lightmapBakeSettings.BounceCount, 1);
}
}
HashSet<LightmapRequestOutputType> requestedNonIntegratedLightmapTypes = GetRequestedNonIntegratedOutputTypes(request);
foreach (LightmapRequestOutputType _ in requestedNonIntegratedLightmapTypes)
calculatedWorkSteps += CalculateNonIntegratedLightmapWorkSteps(currentLightmapDesc.Resolution * currentLightmapDesc.Resolution);
}
}
return calculatedWorkSteps;
}
private static ulong CalculateIntegratedLightmapWorkSteps(uint samplesPerTexel, uint chunkSize, IntegratedOutputType outputType, uint bounces, uint multiplier)
{
uint bouncesMultiplier = outputType == IntegratedOutputType.Indirect
? 0 == bounces ? 1 : bounces
: 1;
return samplesPerTexel*chunkSize*bouncesMultiplier*multiplier;
}
private static ulong CalculateNonIntegratedLightmapWorkSteps(uint lightmapResolution) => lightmapResolution;
private static IntegrationSettings GetIntegrationSettings(in BakeInput bakeInput)
{
var retVal = IntegrationSettings.Default;
retVal.Backend =
bakeInput.lightingSettings.useHardwareRayTracing && RayTracingContext.IsBackendSupported(RayTracingBackend.Hardware) ?
RayTracingBackend.Hardware : RayTracingBackend.Compute;
return retVal;
}
internal static LightmapBakeSettings GetLightmapBakeSettings(in BakeInput bakeInput)
{
// Lightmap settings
LightmapBakeSettings lightmapBakeSettings = new()
{
AOSampleCount = math.max(0, bakeInput.lightingSettings.lightmapSampleCounts.indirectSampleCount),
DirectSampleCount = math.max(0, bakeInput.lightingSettings.lightmapSampleCounts.directSampleCount),
IndirectSampleCount = math.max(0, bakeInput.lightingSettings.lightmapSampleCounts.indirectSampleCount),
BounceCount = math.max(0, bakeInput.lightingSettings.maxBounces),
AOMaxDistance = math.max(0.0f, bakeInput.lightingSettings.aoDistance)
};
lightmapBakeSettings.ValiditySampleCount = lightmapBakeSettings.IndirectSampleCount;
return lightmapBakeSettings;
}
[Flags]
private enum RequestedSubOutput
{
PrimaryTexture = 1 << 0,
DirectionalityTexture = 1 << 1
}
private struct HashedInstanceIndex : IComparable<HashedInstanceIndex>
{
public BakeInstance bakeInstance;
public int texelCount;
public int offsetX;
public int offsetY;
public int hashCode;
public int CompareTo(HashedInstanceIndex other)
{
int size = other.texelCount - texelCount;
if (size != 0)
return size;
int xOffset = other.offsetX - offsetX;
if (xOffset != 0)
return xOffset;
int yOffset = offsetY - other.offsetY;
if (yOffset != 0)
return yOffset;
return hashCode - other.hashCode;
}
};
internal static void SortInstancesByMeshAndResolution(LightmapDesc[] lightmapDescriptors)
{
int lightmapDescIndex = 0;
foreach (var lightmapDesc in lightmapDescriptors)
{
HashedInstanceIndex[] hashedInstances = new HashedInstanceIndex[lightmapDesc.BakeInstances.Length];
int instanceIndex = 0;
foreach (var instance in lightmapDesc.BakeInstances)
{
int hashCode = System.HashCode.Combine(instance.TexelSize.x, instance.TexelSize.y);
hashedInstances[instanceIndex] = new();
hashedInstances[instanceIndex].bakeInstance = instance;
hashedInstances[instanceIndex].texelCount = instance.TexelSize.x * instance.TexelSize.y;
hashedInstances[instanceIndex].offsetX = instance.TexelOffset.x;
hashedInstances[instanceIndex].offsetY = instance.TexelOffset.y;
hashedInstances[instanceIndex].hashCode = hashCode;
instanceIndex++;
}
Array.Sort(hashedInstances);
instanceIndex = 0;
foreach (var hashedInstance in hashedInstances)
{
lightmapDescriptors[lightmapDescIndex].BakeInstances[instanceIndex++] = hashedInstance.bakeInstance;
}
lightmapDescIndex++;
}
}
// Gets all meshes used by the specified instances, ordered by the first instance they are used in.
private static List<Mesh> GetMeshesInInstanceOrder(LightmapDesc[] lightmapDescriptors)
{
List<Mesh> sortedMeshes = new List<Mesh>();
HashSet<Mesh> seenMeshes = new HashSet<Mesh>();
foreach (var lightmapDesc in lightmapDescriptors)
{
foreach (var instance in lightmapDesc.BakeInstances)
{
if (seenMeshes.Add(instance.Mesh))
{
sortedMeshes.Add(instance.Mesh);
}
}
}
return sortedMeshes;
}
private static bool AnyLightmapRequestHasOutput(LightmapRequest[] requests, LightmapRequestOutputType type)
{
foreach (var req in requests)
{
if (req.outputTypeMask.HasFlag(type))
{
return true;
}
}
return false;
}
private static bool EnsureInstanceInCacheAndClearExistingEntries(CommandBuffer cmd,
LightmappingContext lightmappingContext,
BakeInstance bakeInstance)
{
var bakeInstances = new[] { bakeInstance };
if (!lightmappingContext.ResourceCache.CacheIsHot(bakeInstances))
{
// Build the required resources for the current instance
GraphicsHelpers.Flush(cmd); // need to flush as we are removing resources from the cache which might be in use
lightmappingContext.ResourceCache.FreeResources(bakeInstances);
if (!lightmappingContext.ResourceCache.AddResources(
bakeInstances, lightmappingContext.World.RayTracingContext, cmd,
lightmappingContext.IntegratorContext.UVFallbackBufferBuilder))
{
return false;
}
// Flush as there can be a substantial amount of work done in the commandbuffer
GraphicsHelpers.Flush(cmd);
}
return true;
}
private static bool GetInstanceUVResources(
CommandBuffer cmd,
LightmappingContext lightmappingContext,
BakeInstance bakeInstance,
out UVMesh uvMesh,
out UVAccelerationStructure uvAS,
out UVFallbackBuffer uvFallbackBuffer)
{
uvMesh = default;
uvAS = default;
uvFallbackBuffer = default;
if (!EnsureInstanceInCacheAndClearExistingEntries(cmd, lightmappingContext, bakeInstance))
return false;
bool gotResources = lightmappingContext.ResourceCache.GetResources(new[] { bakeInstance },
out UVMesh[] uvMeshes, out UVAccelerationStructure[] uvAccelerationStructures, out UVFallbackBuffer[] uvFallbackBuffers);
if (!gotResources)
return false;
uvMesh = uvMeshes[0];
uvAS = uvAccelerationStructures[0];
uvFallbackBuffer = uvFallbackBuffers[0];
return true;
}
static void GetLodZeroInstanceMasks(bool pathtracingShader, uint[] originalMasks, Span<uint> lodZeroMasks)
{
for (int j = 0; j < originalMasks.Length; j++)
{
// if we don't need bounce rays, we just make the lod0 invisible (instanceMask=0), so that only the current lod can be traced against
// otherwise we set bits so that we can select one or the other using the raymask in the shader
if (pathtracingShader)
{
lodZeroMasks[j] = (uint)InstanceFlags.LOD_ZERO_FOR_LIGHTMAP_INSTANCE;
if ((originalMasks[j] & (uint)InstanceFlags.SHADOW_RAY_VIS_MASK) != 0)
lodZeroMasks[j] |= (uint)InstanceFlags.LOD_ZERO_FOR_LIGHTMAP_INSTANCE_SHADOW;
}
else
{
lodZeroMasks[j] = 0;
}
}
}
static void GetCurrentLodInstanceMasks(bool pathtracingShader, uint[] originalMasks, Span<uint> currentLodMasks)
{
for (int j = 0; j < originalMasks.Length; j++)
{
if (pathtracingShader)
{
currentLodMasks[j] = (uint)InstanceFlags.CURRENT_LOD_FOR_LIGHTMAP_INSTANCE;
if ((originalMasks[j] & (uint)InstanceFlags.SHADOW_RAY_VIS_MASK) != 0)
currentLodMasks[j] |= (uint)InstanceFlags.CURRENT_LOD_FOR_LIGHTMAP_INSTANCE_SHADOW;
}
else
{
currentLodMasks[j] = originalMasks[j];
}
}
}
internal static InstanceHandle[] AddLODInstances(World world, CommandBuffer cmd, LodIdentifier lodIdentifier, in List<LodInstanceBuildData> lodInstancesBuildData, bool pathtracingShader, Dictionary<Int32, List<ContributorLodInfo>> lodgroupToContributorInstances)
{
Debug.Assert(lodIdentifier.IsValid() && !lodIdentifier.IsContributor());
// add current lod instances
var instanceHandles = new InstanceHandle[lodInstancesBuildData.Count];
int i = 0;
uint currentLodLevel = lodIdentifier.MinLodLevelMask();
foreach (LodInstanceBuildData lodBuildData in lodInstancesBuildData)
{
if ((lodBuildData.LodMask & currentLodLevel) == 0)
continue;
Span<uint> currentLodMasks = stackalloc uint[lodBuildData.Masks.Length];
GetCurrentLodInstanceMasks(pathtracingShader, lodBuildData.Masks, currentLodMasks);
instanceHandles[i++] = world.AddInstance(lodBuildData.Mesh, lodBuildData.Materials, currentLodMasks, UnityComputeWorld.RenderingObjectLayer, lodBuildData.LocalToWorldMatrix, lodBuildData.Bounds, lodBuildData.IsStatic, lodBuildData.Filter, true);
}
Array.Resize(ref instanceHandles, i);
// update lod0 instance mask
List<ContributorLodInfo> lodZeroInstances;
if (lodgroupToContributorInstances.TryGetValue(lodIdentifier.LodGroup, out lodZeroInstances))
{
foreach (var lodZeroInstance in lodZeroInstances)
{
if ((lodZeroInstance.LodMask & currentLodLevel) != 0)
continue;
Span<uint> lodZeroMasks = stackalloc uint[lodZeroInstance.Masks.Length];
GetLodZeroInstanceMasks(pathtracingShader, lodZeroInstance.Masks, lodZeroMasks);
world.UpdateInstanceMask(lodZeroInstance.InstanceHandle, lodZeroMasks);
}
}
return instanceHandles;
}
internal static void RemoveLODInstances(World world, CommandBuffer cmd, LodIdentifier lodIdentifier, Span<InstanceHandle> currentLodInstanceHandles, Dictionary<Int32, List<ContributorLodInfo>> lodgroupToContributorInstances)
{
if (!lodIdentifier.IsValid() || lodIdentifier.IsContributor())
return;
// Remove current lod instances
foreach (var instanceHandle in currentLodInstanceHandles)
world.RemoveInstance(instanceHandle);
// Restore lod0 instances
List<ContributorLodInfo> lodZeroInstances;
if (lodgroupToContributorInstances.TryGetValue(lodIdentifier.LodGroup, out lodZeroInstances))
{
foreach (var lodZeroInstance in lodZeroInstances)
world.UpdateInstanceMask(lodZeroInstance.InstanceHandle, lodZeroInstance.Masks);
}
}
private static InstanceHandle[] PrepareLodInstances(
CommandBuffer cmd,
UnityComputeWorld world,
BakeInstance bakeInstance,
Dictionary<int, List<LodInstanceBuildData>> lodInstances,
Dictionary<Int32, List<ContributorLodInfo>> lodgroupToContributorInstances,
bool isPathTracingPass)
{
if (bakeInstance.LodIdentifier.IsValid() && !bakeInstance.LodIdentifier.IsContributor())
{
// AddLODInstances calls _pathTracingWorld.Add/RemoveInstance(...) that doesn't take a cmd buffer arg. Need to flush as cmdbuffer and immediate calls cannot be mixed.
GraphicsHelpers.Flush(cmd);
var currentLodInstancesBuildData = lodInstances[bakeInstance.LodIdentifier.LodGroup];
InstanceHandle[] handles = AddLODInstances(world.PathTracingWorld, cmd, bakeInstance.LodIdentifier, currentLodInstancesBuildData, isPathTracingPass, lodgroupToContributorInstances);
world.BuildAccelerationStructure(cmd);
return handles;
}
return null;
}
private static void ClearLodInstances(
CommandBuffer cmd,
UnityComputeWorld world,
BakeInstance bakeInstance,
InstanceHandle[] currentLodInstances,
Dictionary<Int32, List<ContributorLodInfo>> lodgroupToContributorInstances)
{
if (bakeInstance.LodIdentifier.IsValid() && !bakeInstance.LodIdentifier.IsContributor())
{
// RemoveLODInstances calls _pathTracingWorld.Add/RemoveInstance(...) that doesn't take a cmd buffer arg. Need to flush as cmdbuffer and immediate calls cannot be mixed.
GraphicsHelpers.Flush(cmd);
RemoveLODInstances(world.PathTracingWorld, cmd, bakeInstance.LodIdentifier, currentLodInstances, lodgroupToContributorInstances);
world.BuildAccelerationStructure(cmd);
}
}
private static Result IntegrateLightmapInstance(CommandBuffer cmd,
int lightmapIndex,
IntegratedOutputType integratedOutputType,
BakeInstance bakeInstance,
in Dictionary<int, List<LodInstanceBuildData>> lodInstances,
in Dictionary<Int32, List<ContributorLodInfo>> lodgroupToContributorInstances,
LightmappingContext lightmappingContext,
UVAccelerationStructure uvAS,
UVFallbackBuffer uvFallbackBuffer,
IntegrationSettings integrationSettings,
LightmapBakeSettings lightmapBakeSettings,
bool doDirectionality,
BakeProgressState progressState,
LightmapIntegrationHelpers.GPUSync gpuSync,
bool debugDispatches)
{
Debug.Assert(!lightmappingContext.ExpandedBufferNeedsUpdating(lightmapBakeSettings.ExpandedBufferSize), "The integration data must be allocated at this point.");
// Bake the lightmap instances
int bakeDispatches = 0;
LightmapBakeState bakeState = new();
bakeState.Init();
uint samples = 0;
bool isInstanceDone = false;
uint dispatchCount = 0;
uint instanceWidth = (uint)bakeInstance.TexelSize.x;
uint instanceHeight = (uint)bakeInstance.TexelSize.y;
InstanceHandle[] currentLodInstances = null;
// accumulate the instance
System.Diagnostics.Stopwatch instanceFlushStopwatch = System.Diagnostics.Stopwatch.StartNew();
System.Diagnostics.Stopwatch dispatchStopwatch = System.Diagnostics.Stopwatch.StartNew();
do
{
if (debugDispatches)
{
gpuSync.Sync(cmd);
dispatchStopwatch.Restart();
Console.WriteLine($"Begin pass {bakeDispatches} for lm: {lightmapIndex}, type: {integratedOutputType}, sample count: {bakeState.SampleIndex}, res: [{bakeInstance.TexelSize.x} x {bakeInstance.TexelSize.y}], offset: [{bakeInstance.TexelOffset.x} x {bakeInstance.TexelOffset.y}].");
}
bool isInstanceStart = (bakeState.SampleIndex == 0);
if (isInstanceStart)
{
bool isPathTracingPass = integratedOutputType == IntegratedOutputType.Indirect || integratedOutputType == IntegratedOutputType.DirectionalityIndirect;
currentLodInstances = PrepareLodInstances(cmd, lightmappingContext.World, bakeInstance, lodInstances, lodgroupToContributorInstances, isPathTracingPass);
}
// Enqueue some baking work in the command buffer.
cmd.BeginSample($"Bake {integratedOutputType}");
dispatchCount++;
uint passSamplesPerTexel = BakeLightmapDriver.AccumulateLightmapInstance(
bakeState,
bakeInstance,
lightmapBakeSettings,
integratedOutputType,
lightmappingContext,
uvAS,
uvFallbackBuffer,
doDirectionality,
out uint chunkSize,
out isInstanceDone);
samples += instanceWidth * instanceHeight * passSamplesPerTexel;
cmd.EndSample($"Bake {integratedOutputType}");
if (isInstanceDone)
{
ClearLodInstances(cmd, lightmappingContext.World, bakeInstance, currentLodInstances, lodgroupToContributorInstances);
}
if (debugDispatches)
{
gpuSync.Sync(cmd);
dispatchStopwatch.Stop();
Console.WriteLine($"Finished pass {bakeDispatches}. Elapsed ms: {dispatchStopwatch.ElapsedMilliseconds}");
}
bakeDispatches++;
// Execute the baking work scheduled in BakeLightmaps.
if (bakeDispatches % integrationSettings.MaxDispatchesPerFlush != 0 && !isInstanceDone)
continue;
// Chip-off work steps based on the chunk done so far
ulong completedWorkSteps =
CalculateIntegratedLightmapWorkSteps(passSamplesPerTexel, chunkSize, integratedOutputType, lightmapBakeSettings.BounceCount, integrationSettings.MaxDispatchesPerFlush);
gpuSync.RequestAsyncReadback(cmd, _ => progressState.IncrementCompletedWorkSteps(completedWorkSteps));
GraphicsHelpers.Flush(cmd);
if (!debugDispatches)
continue;
gpuSync.Sync(cmd);
instanceFlushStopwatch.Stop();
Console.WriteLine($"Bake dispatch flush -> Instance: {bakeInstance.Mesh.GetEntityId()}, dispatches {dispatchCount}, Samples: \t{samples}\t. Elapsed ms:\t{instanceFlushStopwatch.ElapsedMilliseconds}");
samples = 0;
dispatchCount = 0;
instanceFlushStopwatch.Restart();
//LightmapIntegrationHelpers.WriteRenderTexture(cmd, $"Temp/lm{lightmapIndex}_type{lightmapType}_pass{bakeDispatches}.r2d", lightmappingContext.AccumulatedOutput, lightmappingContext.AccumulatedOutput.width, lightmappingContext.AccumulatedOutput.height);
}
while (isInstanceDone == false);
return Result.Success;
}
internal static Result ExecuteLightmapRequests(
in LightmapRequestData lightmapRequestData,
UnityComputeDeviceContext deviceContext,
UnityComputeWorld world,
in FatInstance[] fatInstances,
in Dictionary<int, List<LodInstanceBuildData>> lodInstances,
in Dictionary<Int32, List<ContributorLodInfo>> lodgroupToContributorInstances,
IntegrationSettings integrationSettings,
bool useLegacyBakingBehavior,
LightmapResourceLibrary lightmapResourceLib,
BakeProgressState progressState,
LightmapDesc[] lightmapDescriptors,
LightmapBakeSettings lightmapBakeSettings,
UnityEngine.Rendering.Sampling.SamplingResources samplingResources)
{
using var lightmappingContext = new LightmappingContext();
bool debugDispatches = integrationSettings.DebugDispatches;
bool doDirectionality = AnyLightmapRequestHasOutput(lightmapRequestData.requests, LightmapRequestOutputType.DirectionalityDirect) || AnyLightmapRequestHasOutput(lightmapRequestData.requests, LightmapRequestOutputType.DirectionalityIndirect);
// Find the max index and vertex count in any mesh, so we can pre-allocate various buffers based on it.
uint maxIndexCount = 1;
uint maxVertexCount = 1;
for (int meshIdx = 0; meshIdx < world.Meshes.Length; ++meshIdx)
{
maxIndexCount = Math.Max(maxIndexCount, world.Meshes[meshIdx].GetTotalIndexCount());
maxVertexCount = Math.Max(maxVertexCount, (uint)world.Meshes[meshIdx].vertexCount);
}
(int width, int height)[] atlasSizes = lightmapRequestData.atlassing.m_AtlasSizes;
int initialLightmapResolution = atlasSizes.Length > 0 ? atlasSizes[0].width : 1024;
if (!lightmappingContext.Initialize(deviceContext, initialLightmapResolution, initialLightmapResolution, world, maxIndexCount, maxVertexCount, lightmapResourceLib))
return Result.InitializeFailure;
lightmappingContext.IntegratorContext.Initialize(samplingResources, lightmapResourceLib, !useLegacyBakingBehavior);
// Chart identification happens in multithreaded fashion on the CPU. We start it immediately so it can run in tandem with other work.
bool usesChartIdentification = AnyLightmapRequestHasOutput(lightmapRequestData.requests, LightmapRequestOutputType.ChartIndex) ||
AnyLightmapRequestHasOutput(lightmapRequestData.requests, LightmapRequestOutputType.OverlapPixelIndex);
using ParallelChartIdentification chartIdentification = usesChartIdentification ? new ParallelChartIdentification(GetMeshesInInstanceOrder(lightmapDescriptors)) : null;
if (usesChartIdentification)
chartIdentification.Start();
if (debugDispatches)
{
for (int i = 0; i < lightmapDescriptors.Length; ++i)
{
Console.WriteLine($"Desc:");
int instanceIndex = 0;
foreach (var bakeInstance in lightmapDescriptors[i].BakeInstances)
Console.WriteLine($" Instance[{instanceIndex++}]: {bakeInstance.Mesh.GetEntityId()}, res: [{bakeInstance.TexelSize.x} x {bakeInstance.TexelSize.y}], offset: [{bakeInstance.TexelOffset.x} x {bakeInstance.TexelOffset.y}].");
}
}
CommandBuffer cmd = lightmappingContext.GetCommandBuffer();
using LightmapIntegrationHelpers.GPUSync gpuSync = new(); // used for sync points in debug mode
gpuSync.Create();
// process requests
for (int requestIndex = 0; requestIndex < lightmapRequestData.requests.Length; requestIndex++)
{
if (progressState.WasCancelled())
return Result.Cancelled;
ref readonly var request = ref lightmapRequestData.requests[requestIndex];
if (request.lightmapCount == 0)
continue;
var createDirResult = Directory.CreateDirectory(request.outputFolderPath);
if (createDirResult.Exists == false)
return Result.CreateDirectoryFailure;
Dictionary<IntegratedOutputType, RequestedSubOutput> integratedRequestOutputs = GetRequestedIntegratedOutputTypes(request);
bool needsNormalsForDirectionality = request.outputTypeMask.HasFlag(LightmapRequestOutputType.DirectionalityIndirect) || request.outputTypeMask.HasFlag(LightmapRequestOutputType.DirectionalityDirect);
bool writeNormals = request.outputTypeMask.HasFlag(LightmapRequestOutputType.Normal);
// Request related bake settings
for (int lightmapIndex = 0; lightmapIndex < request.lightmapCount; lightmapIndex++)
{
if (progressState.WasCancelled())
return Result.Cancelled;
LightmapDesc currentLightmapDesc = lightmapDescriptors[lightmapIndex];
lightmapBakeSettings.PushOff = currentLightmapDesc.PushOff;
int resolution = (int)currentLightmapDesc.Resolution;
UInt64 lightmapSize = (UInt64)resolution * (UInt64)resolution;
lightmapBakeSettings.ExpandedBufferSize = LightmapRequest.TilingModeToLightmapExpandedBufferSize(request.tilingMode);
// allocate expanded buffer
if (lightmappingContext.ExpandedBufferNeedsUpdating(lightmapBakeSettings.ExpandedBufferSize))
{
GraphicsHelpers.Flush(cmd); // need to flush as we are removing resources from the cache which might be in use
if (!lightmappingContext.InitializeExpandedBuffer(lightmapBakeSettings.ExpandedBufferSize))
return Result.InitializeExpandedBufferFailure;
// The scratch buffer is used for tracing rays in the lightmap integrators it needs to be sufficiently large to ray trace an expanded buffer
uint scratchBufferSize = (uint)lightmapBakeSettings.ExpandedBufferSize;
lightmappingContext.InitializeTraceScratchBuffer(scratchBufferSize, 1, 1);
if (debugDispatches)
Console.WriteLine($"Built expanded buffer for {lightmapBakeSettings.ExpandedBufferSize} samples, lm w: {lightmappingContext.AccumulatedOutput.width}, lm h: {lightmappingContext.AccumulatedOutput.height}].");
}
ref RenderTexture accumulatedOutput = ref lightmappingContext.AccumulatedOutput;
if ((accumulatedOutput.width != resolution) || (accumulatedOutput.height != resolution))
if (!lightmappingContext.SetOutputResolution(resolution, resolution))
return Result.InitializeFailure;
// Bake normals output
RenderTexture normalBuffer = null;
if (needsNormalsForDirectionality || writeNormals)
{
lightmappingContext.ClearOutputs();
IRayTracingShader normalShader = lightmapResourceLib.NormalAccumulationShader;
GraphicsBuffer compactedGBufferLength = lightmappingContext.CompactedGBufferLength;
GraphicsBuffer indirectDispatchBuffer = lightmappingContext.IndirectDispatchBuffer;
GraphicsBuffer indirectRayTracingDispatchBuffer = lightmappingContext.IndirectDispatchRayTracingBuffer;
uint maxChunkSize = (uint)lightmappingContext.ExpandedOutput.count;
var expansionShaders = lightmapResourceLib.ExpansionHelpers;
var compactionKernel = expansionShaders.FindKernel("CompactGBuffer");
var populateCopyDispatchKernel = expansionShaders.FindKernel("PopulateCopyDispatch");
var copyToLightmapKernel = expansionShaders.FindKernel("AdditivelyCopyCompactedTo2D");
var populateNormalShaderDispatchKernel = expansionShaders.FindKernel("PopulateAccumulationDispatch");
expansionShaders.GetKernelThreadGroupSizes(copyToLightmapKernel, out uint copyThreadGroupSizeX, out uint copyThreadGroupSizeY, out uint copyThreadGroupSizeZ);
Debug.Assert(copyThreadGroupSizeY == 1 && copyThreadGroupSizeZ == 1);
foreach (var bakeInstance in currentLightmapDesc.BakeInstances)
{
if (progressState.WasCancelled())
return Result.Cancelled;
if (!GetInstanceUVResources(cmd, lightmappingContext, bakeInstance, out _, out var uvAS, out var uvFallbackBuffer))
return Result.AddResourcesToCacheFailure;