-
Notifications
You must be signed in to change notification settings - Fork 868
Expand file tree
/
Copy pathInstanceCuller.cs
More file actions
2859 lines (2418 loc) · 133 KB
/
InstanceCuller.cs
File metadata and controls
2859 lines (2418 loc) · 133 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.Threading;
using UnityEngine.Assertions;
using Unity.Burst;
using Unity.Burst.CompilerServices;
using Unity.Mathematics;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine.SceneManagement;
using UnityEngine.Rendering.RenderGraphModule;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Rendering;
using UnityEditor.SceneManagement;
#endif
namespace UnityEngine.Rendering
{
internal struct RangeKey : IEquatable<RangeKey>
{
public byte layer;
public uint renderingLayerMask;
public MotionVectorGenerationMode motionMode;
public ShadowCastingMode shadowCastingMode;
public bool staticShadowCaster;
public int rendererPriority;
public bool supportsIndirect;
public bool Equals(RangeKey other)
{
return layer == other.layer
&& renderingLayerMask == other.renderingLayerMask
&& motionMode == other.motionMode
&& shadowCastingMode == other.shadowCastingMode
&& staticShadowCaster == other.staticShadowCaster
&& rendererPriority == other.rendererPriority
&& supportsIndirect == other.supportsIndirect;
}
public override int GetHashCode()
{
int hash = 13;
hash = (hash * 23) + layer;
hash = (hash * 23) + (int)renderingLayerMask;
hash = (hash * 23) + (int)motionMode;
hash = (hash * 23) + (int)shadowCastingMode;
hash = (hash * 23) + (staticShadowCaster ? 1 : 0);
hash = (hash * 23) + rendererPriority;
hash = (hash * 23) + (supportsIndirect ? 1 : 0);
return hash;
}
}
internal struct DrawRange
{
public RangeKey key;
public int drawCount;
public int drawOffset;
}
internal struct DrawKey : IEquatable<DrawKey>
{
public EntityId transparentInstanceID; // non-zero for transparent instances, to ensure each instance has its own draw command (for sorting)
public BatchMeshID meshID;
public int submeshIndex;
public int activeMeshLod; // or -1 if this draw is not using mesh LOD
public BatchMaterialID materialID;
public BatchDrawCommandFlags flags;
public GPUArchetypeHandle archetype;
public RangeKey range;
public int lightmapIndex;
public bool Equals(DrawKey other)
{
return meshID == other.meshID
&& submeshIndex == other.submeshIndex
&& activeMeshLod == other.activeMeshLod
&& materialID == other.materialID
&& flags == other.flags
&& transparentInstanceID == other.transparentInstanceID
&& archetype.Equals(other.archetype)
&& range.Equals(other.range)
&& lightmapIndex == other.lightmapIndex;
}
public override int GetHashCode()
{
int hash = 13;
hash = (hash * 23) + (int)meshID.value;
hash = (hash * 23) + (int)submeshIndex;
hash = (hash * 23) + (int)activeMeshLod;
hash = (hash * 23) + (int)materialID.value;
hash = (hash * 23) + (int)flags;
hash = (hash * 23) + (int)transparentInstanceID.GetRawData();
hash = (hash * 23) + range.GetHashCode();
hash = (hash * 23) + archetype.index;
hash = (hash * 23) + lightmapIndex;
return hash;
}
}
internal struct DrawBatch
{
public DrawKey key;
public int instanceCount;
public int instanceOffset;
public MeshTopology topology;
public uint baseVertex;
public uint firstIndex;
public uint indexCount;
}
internal struct DrawInstance
{
public DrawKey key;
public int instanceIndex;
}
internal struct BinningConfig
{
public int viewCount;
public bool supportsCrossFade;
public bool supportsMotionCheck;
public int visibilityConfigCount
{
get
{
// always bin based on flip winding state (the initial 1 bit)
int bitCount = 1 + viewCount + (supportsCrossFade ? 1 : 0) + (supportsMotionCheck ? 1 : 0);
return 1 << bitCount;
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal struct AnimateCrossFadeJob : IJobParallelFor
{
public const int k_BatchSize = 512;
public const byte k_MeshLodTransitionToLowerLodBit = 0x80;
private const byte k_LODFadeOff = (byte)CullingJob.k_LODFadeOff;
private const float k_CrossfadeAnimationTimeS = 0.333f;
[ReadOnly] public float deltaTime;
public NativeArray<byte> crossFadeArray;
public unsafe void Execute(int instanceIndex)
{
ref var crossFadeValue = ref crossFadeArray.ElementAtRW(instanceIndex);
if (crossFadeValue == k_LODFadeOff)
return;
var prevTransitionBit = (crossFadeValue & k_MeshLodTransitionToLowerLodBit);
crossFadeValue += (byte)((deltaTime / k_CrossfadeAnimationTimeS) * 127.0f);
//If done with crossfade - reset mask
if (prevTransitionBit != ((crossFadeValue + 1) & k_MeshLodTransitionToLowerLodBit))
crossFadeValue = k_LODFadeOff;
}
}
[BurstCompile]
internal struct CullingJob : IJobParallelFor
{
public const uint k_MeshLodCrossfadeActive = 0x40;
public const uint k_MeshLodCrossfadeSignBit = 0x80;
public const uint k_MeshLodCrossfadeBits = k_MeshLodCrossfadeSignBit | k_MeshLodCrossfadeActive;
public const uint k_LODFadeOff = 255u;
public const uint k_LODFadeZeroPacked = 127u;
public const uint k_LODFadeIsSpeedTree = 256u;
private const uint k_InvalidCrossFadeAndLevel = 0xFFFFFFFF;
const uint k_VisibilityMaskNotVisible = 0u;
const float k_SmallMeshTransitionWidth = 0.1f;
enum CrossFadeType
{
kDisabled,
kCrossFadeOut, // 1 == instance is visible in current lod, and not next - could be fading out
kCrossFadeIn, // 2 == instance is visible in next lod level, but not current - could be fading in
kVisible // 3 == instance is visible in both current and next lod level - could not be impacted by fade
}
[ReadOnly] public RenderWorld renderWorld;
[ReadOnly] public NativeParallelHashMap<EntityId, MeshInfo> meshMap;
[ReadOnly] public BinningConfig binningConfig;
[ReadOnly] public BatchCullingViewType viewType;
[ReadOnly] public float3 cameraPosition;
[ReadOnly] public float sqrMeshLodSelectionConstant;
[ReadOnly] public float sqrScreenRelativeMetric;
[ReadOnly] public float minScreenRelativeHeight;
[ReadOnly] public bool isOrtho;
[ReadOnly] public bool cullLightmappedShadowCasters;
[ReadOnly] public int maxLOD;
[ReadOnly] public uint cullingLayerMask;
[ReadOnly] public ulong sceneCullingMask;
[ReadOnly] public float3x3 worldToLightSpaceRotation;
[ReadOnly] public bool animateCrossFades;
[ReadOnly] public NativeArray<FrustumPlaneCuller.PlanePacket4> frustumPlanePackets;
[ReadOnly] public NativeArray<FrustumPlaneCuller.SplitInfo> frustumSplitInfos;
[ReadOnly] public NativeArray<Plane> lightFacingFrustumPlanes;
[ReadOnly] public NativeArray<ReceiverSphereCuller.SplitInfo> receiverSplitInfos;
#if UNITY_EDITOR
[ReadOnly] public IncludeExcludeListFilter includeExcludeListFilter;
#endif
[NativeDisableContainerSafetyRestriction, NoAlias][ReadOnly] public NativeList<LODGroupCullingData> lodGroupCullingData;
[NativeDisableUnsafePtrRestriction][ReadOnly] public IntPtr occlusionBuffer;
[NativeDisableParallelForRestriction][WriteOnly] public NativeArray<byte> rendererVisibilityMasks;
[NativeDisableParallelForRestriction][WriteOnly] public NativeArray<byte> rendererMeshLodSettings;
[NativeDisableParallelForRestriction][WriteOnly] public NativeArray<byte> rendererCrossFadeValues;
public RenderWorld.PerCameraInstanceData perCameraInstanceData;
// float [-1.0f... 1.0f] -> uint [0...254]
static uint PackFloatToUint8(float percent)
{
uint packed = (uint)((1.0f + percent) * 127.0f + 0.5f);
// avoid zero
return percent < 0.0f
? math.clamp(packed, 0, 126)
: math.clamp(packed, 128, 254);
}
unsafe uint CalculateLODVisibility(int instanceIndex, bool smallMeshCulling)
{
GPUInstanceIndex lodGroupIndex = renderWorld.lodGroupIndices[instanceIndex];
uint lodMask = renderWorld.lodMasks[instanceIndex];
if (lodGroupIndex.Equals(GPUInstanceIndex.Invalid) && lodMask == 0)
{
if (viewType >= BatchCullingViewType.SelectionOutline || !smallMeshCulling || minScreenRelativeHeight == 0.0f)
return k_LODFadeOff;
// If no LODGroup available - small mesh culling.
ref readonly AABB worldAABB = ref renderWorld.worldAABBs.ElementAt(instanceIndex);
var cameraSqrDist = isOrtho ? sqrScreenRelativeMetric : LODRenderingUtils.CalculateSqrPerspectiveDistance(worldAABB.center, cameraPosition, sqrScreenRelativeMetric);
var cameraDist = math.sqrt(cameraSqrDist);
var aabbSize = worldAABB.extents * 2.0f;
var worldSpaceSize = math.max(math.max(aabbSize.x, aabbSize.y), aabbSize.z);
var maxDist = LODRenderingUtils.CalculateLODDistance(minScreenRelativeHeight, worldSpaceSize);
if (maxDist < cameraDist)
return k_LODFadeZeroPacked;
var transitionHeight = minScreenRelativeHeight + k_SmallMeshTransitionWidth * minScreenRelativeHeight;
var fadeOutRange = Mathf.Max(0.0f,maxDist - LODRenderingUtils.CalculateLODDistance(transitionHeight, worldSpaceSize));
var lodPercent = (maxDist - cameraDist) / fadeOutRange;
return lodPercent > 1.0f ? k_LODFadeOff : PackFloatToUint8(lodPercent);
}
Assert.IsTrue(lodMask > 0);
ref var lodGroup = ref lodGroupCullingData.ElementAt(lodGroupIndex.index);
if (lodGroup.forceLODMask != 0)
return (lodGroup.forceLODMask & lodMask) != 0 ? k_LODFadeOff : k_LODFadeZeroPacked;
float cameraSqrDistToLODCenter = isOrtho ? sqrScreenRelativeMetric : LODRenderingUtils.CalculateSqrPerspectiveDistance(lodGroup.worldSpaceReferencePoint, cameraPosition, sqrScreenRelativeMetric);
// Remove lods that are beyond the max lod.
uint maxLodMask = 0xffffffff << maxLOD;
lodMask &= maxLodMask;
// Offset to the lod preceding the first for proper cross fade calculation.
int m = math.max(math.tzcnt(lodMask) - 1, maxLOD);
lodMask >>= m;
while (lodMask > 0)
{
var lodRangeSqrMin = m == maxLOD ? 0.0f : lodGroup.sqrDistances[m - 1];
var lodRangeSqrMax = lodGroup.sqrDistances[m];
// Camera is beyond the range of this all further lods. No need to proceed.
if (cameraSqrDistToLODCenter < lodRangeSqrMin)
break;
if (cameraSqrDistToLODCenter > lodRangeSqrMax)
{
++m;
lodMask >>= 1;
continue;
}
// Instance is in the min/max range of this lod. Proceeding.
var type = (CrossFadeType)(lodMask & 3);
// Instance is in neither this LOD Level nor next - invisible
if (type == CrossFadeType.kDisabled)
return k_LODFadeZeroPacked;
// Instance is in both this and the next lod. No need to fade - fully visible
if (type == CrossFadeType.kVisible)
return k_LODFadeOff;
var distanceToLodCenter = math.sqrt(cameraSqrDistToLODCenter);
var maxDist = math.sqrt(lodRangeSqrMax);
// SpeedTree cross fade.
if (lodGroup.percentageFlags[m])
{
// The fading-in instance is not visible but the fading-out is visible and it does the speed tree vertex deformation.
if (type == CrossFadeType.kCrossFadeIn)
{
return k_LODFadeZeroPacked + 1;
}
else if (type == CrossFadeType.kCrossFadeOut)
{
var minDist = m > 0
? math.sqrt(lodGroup.sqrDistances[m - 1])
: lodGroup.worldSpaceSize;
var lodPercent = math.max(distanceToLodCenter - minDist, 0.0f) / (maxDist - minDist);
return PackFloatToUint8(lodPercent) | k_LODFadeIsSpeedTree;
}
}
// Dithering cross fade.
else
{
var transitionDist = lodGroup.transitionDistances[m];
var dif = maxDist - distanceToLodCenter;
// If in the transition zone, both fading-in and fading-out instances are visible. Calculate the lod percent.
// If not then only the fading-out instance is fully visible, and fading-in is invisible.
if (dif < transitionDist)
{
var lodPercent = dif / transitionDist;
if (type == CrossFadeType.kCrossFadeIn)
lodPercent = -lodPercent;
return PackFloatToUint8(lodPercent);
}
return type == CrossFadeType.kCrossFadeOut ? k_LODFadeOff : k_LODFadeZeroPacked;
}
}
return k_LODFadeZeroPacked;
}
private uint CalculateVisibilityMask(int instanceIndex, ShadowCastingMode shadowCastingMode, bool affectsLightmaps)
{
if (!renderWorld.renderingEnabled.Get(instanceIndex))
return 0;
if (cullingLayerMask == 0)
return 0;
if ((cullingLayerMask & (1 << renderWorld.rendererSettings[instanceIndex].ObjectLayer)) == 0)
return 0;
if (cullLightmappedShadowCasters && affectsLightmaps)
return 0;
#if UNITY_EDITOR
if ((sceneCullingMask & renderWorld.sceneCullingMasks[instanceIndex]) == 0)
return 0;
if (viewType == BatchCullingViewType.SelectionOutline && !includeExcludeListFilter.DoesPassFilter(renderWorld.instanceIDs[instanceIndex]))
return 0;
#endif
// cull early for camera and shadow views based on the shadow culling mode
if (viewType == BatchCullingViewType.Camera && shadowCastingMode == ShadowCastingMode.ShadowsOnly)
return 0;
if (viewType == BatchCullingViewType.Light && shadowCastingMode == ShadowCastingMode.Off)
return 0;
ref readonly AABB worldAABB = ref renderWorld.worldAABBs.ElementAt(instanceIndex);
uint visibilityMask = FrustumPlaneCuller.ComputeSplitVisibilityMask(frustumPlanePackets, frustumSplitInfos, worldAABB);
if (visibilityMask != 0 && receiverSplitInfos.Length > 0)
visibilityMask &= ReceiverSphereCuller.ComputeSplitVisibilityMask(lightFacingFrustumPlanes, receiverSplitInfos, worldToLightSpaceRotation, worldAABB);
// Perform an occlusion test on the instance bounds if we have an occlusion buffer available and the instance is still visible
if (visibilityMask != 0 && occlusionBuffer != IntPtr.Zero)
visibilityMask = BatchRendererGroup.OcclusionTestAABB(occlusionBuffer, worldAABB.ToBounds()) ? visibilityMask : 0;
return visibilityMask;
}
// Algorithm is detailed and must be kept in sync with CalculateMeshLod (C++)
private uint ComputeMeshLODLevel(int instanceIndex, in MeshInfo mesh)
{
InternalMeshLodRendererSettings meshLodSettings = renderWorld.meshLodRendererSettings[instanceIndex];
if (meshLodSettings.forceLod >= 0)
return (uint)math.clamp(meshLodSettings.forceLod, 0, mesh.meshLodCount - 1);
Mesh.LodSelectionCurve lodSelectionCurve = mesh.meshLodSelectionCurve;
ref readonly AABB worldAABB = ref renderWorld.worldAABBs.ElementAt(instanceIndex);
var radiusSqr = math.max(math.lengthsq(worldAABB.extents), 1e-5f);
var diameterSqr = radiusSqr * 4;
var cameraSqrHeightAtDistance = isOrtho ? sqrMeshLodSelectionConstant :
LODRenderingUtils.CalculateSqrPerspectiveDistance(worldAABB.center, cameraPosition, sqrMeshLodSelectionConstant);
var boundsDesiredPercentage = Math.Sqrt(cameraSqrHeightAtDistance / diameterSqr);
var levelIndexFlt = math.log2(boundsDesiredPercentage) * lodSelectionCurve.lodSlope + lodSelectionCurve.lodBias;
// We apply Bias after max to enforce that a positive bias of +N we would select lodN instead of Lod0
levelIndexFlt = math.max(levelIndexFlt, 0);
levelIndexFlt += meshLodSettings.lodSelectionBias;
levelIndexFlt = math.clamp(levelIndexFlt, 0, mesh.meshLodCount - 1);
return (uint)math.floor(levelIndexFlt);
}
// A crossfading instance is assigned a [0.0(invisible) - 1.0(fully visible)] value.
// The complementary instance is assigned the negative of this value[-1.0(invisible) - -0.0(fully visible)]
// As we pack it to a 8-bit uint, we transition from [0-126] when transitioning from a Lower to a higher LOD level,
// and from [127-254] when transitioning from a higher to a lower LOD level.
// This means that we can use (k_MeshLODTransitionToLowerLODBit = 0x80) to select the correct instance to blend with during draw command generation.
private unsafe uint ComputeMeshLODCrossfade(int instanceIndex, ref uint meshLodLevel)
{
var previousLodLevel = perCameraInstanceData.meshLods[instanceIndex];
//1st frame - previous LOD level is invalid. Just update it and return.
if (previousLodLevel == 0xff)
{
perCameraInstanceData.meshLods[instanceIndex] = (byte)meshLodLevel;
return k_LODFadeOff;
}
var currentCrossFade = perCameraInstanceData.crossFades[instanceIndex];
// If not already crossfading, check if we changed Lod level this frame, and starts crossfading.
if (currentCrossFade == k_LODFadeOff)
{
if (previousLodLevel == meshLodLevel)
return k_LODFadeOff;
perCameraInstanceData.meshLods[instanceIndex] = (byte)meshLodLevel;
perCameraInstanceData.crossFades[instanceIndex] = (byte)(meshLodLevel < previousLodLevel ? AnimateCrossFadeJob.k_MeshLodTransitionToLowerLodBit : 1);
meshLodLevel = previousLodLevel;
return k_LODFadeOff;
}
//On the first crossfading frame, other cameras could have set the current crossfade values, but we do not want to fade until next frame.
if ((currentCrossFade - 1) % k_LODFadeZeroPacked == 0)
{
meshLodLevel = previousLodLevel;
return k_LODFadeOff;
}
meshLodLevel = previousLodLevel | (currentCrossFade > k_LODFadeZeroPacked ? k_MeshLodCrossfadeBits : k_MeshLodCrossfadeActive);
return currentCrossFade;
}
private unsafe void EnforcePreviousFrameMeshLOD(int instanceIndex, ref uint meshLodLevel)
{
ref var previousLodLevel = ref perCameraInstanceData.meshLods.ElementAtRW(instanceIndex);
if (previousLodLevel != k_LODFadeOff)
meshLodLevel = previousLodLevel;
}
public void Execute(int instanceIndex)
{
InstanceHandle instance = renderWorld.indexToHandle[instanceIndex];
InternalMeshRendererSettings rendererSettings = renderWorld.rendererSettings[instanceIndex];
bool affectsLightmaps = LightmapUtils.AffectsLightmaps(renderWorld.lightmapIndices[instanceIndex]);
var visibilityMask = CalculateVisibilityMask(instanceIndex, rendererSettings.ShadowCastingMode, affectsLightmaps);
if (visibilityMask == k_VisibilityMaskNotVisible)
{
rendererVisibilityMasks[instance.index] = (byte)k_VisibilityMaskNotVisible;
return;
}
var crossFadeValue = CalculateLODVisibility(instanceIndex, rendererSettings.SmallMeshCulling);
if (crossFadeValue == k_LODFadeZeroPacked)
{
rendererVisibilityMasks[instance.index] = (byte)k_VisibilityMaskNotVisible;
return;
}
if (binningConfig.supportsMotionCheck)
{
bool hasMotion = renderWorld.movedInPreviousFrameBits.Get(instanceIndex);
visibilityMask = (visibilityMask << 1) | (hasMotion ? 1U : 0);
}
EntityId meshID = renderWorld.meshIDs[instanceIndex];
MeshInfo mesh = meshMap[meshID];
bool hasMeshLod = mesh.isLodSelectionActive;
// select mesh LOD level
uint meshLodLevel = 0u;
if (hasMeshLod)
meshLodLevel = ComputeMeshLODLevel(instanceIndex, mesh);
if (binningConfig.supportsCrossFade)
{
if (hasMeshLod && animateCrossFades)
{
//Only Crossfade mesh LOD if we aren't already crossfading through LOD groups or SpeedTree
if (crossFadeValue == k_LODFadeOff)
{
crossFadeValue = ComputeMeshLODCrossfade(instanceIndex, ref meshLodLevel);
}
else
{
// If we are cross fading through LODGroup, we reuse previous frame's LodLevel to avoid popping
EnforcePreviousFrameMeshLOD(instanceIndex, ref meshLodLevel);
}
}
// if crossfade is 255 or more, either crossfade is off or it's speedTreeFade, cases for which we do not need to set the fade bit.
visibilityMask = (visibilityMask << 1) | (crossFadeValue < k_LODFadeOff ? 1U : 0);
}
rendererVisibilityMasks[instance.index] = (byte)visibilityMask;
rendererMeshLodSettings[instance.index] = (byte)meshLodLevel;
rendererCrossFadeValues[instance.index] = (byte)(crossFadeValue & 0xFF);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal unsafe struct AllocateBinsPerBatch : IJobParallelFor
{
[ReadOnly] public BinningConfig binningConfig;
[ReadOnly] public NativeList<DrawBatch> drawBatches;
[ReadOnly] public NativeArray<int> drawInstanceIndices;
[ReadOnly] public RenderWorld renderWorld;
[ReadOnly] public NativeArray<byte> rendererVisibilityMasks;
[ReadOnly] public NativeArray<byte> rendererMeshLodSettings;
[NativeDisableContainerSafetyRestriction, NoAlias] [WriteOnly] public NativeArray<int> batchBinAllocOffsets;
[NativeDisableContainerSafetyRestriction, NoAlias] [WriteOnly] public NativeArray<int> batchBinCounts;
[NativeDisableContainerSafetyRestriction, NoAlias] [DeallocateOnJobCompletion] public NativeArray<int> binAllocCounter;
[NativeDisableContainerSafetyRestriction, NoAlias] [WriteOnly] public NativeArray<short> binConfigIndices;
[NativeDisableContainerSafetyRestriction, NoAlias] [WriteOnly] public NativeArray<int> binVisibleInstanceCounts;
[ReadOnly] public int debugCounterIndexBase;
[NativeDisableContainerSafetyRestriction, NoAlias] public NativeArray<int> splitDebugCounters;
bool IsInstanceFlipped(int rendererIndex)
{
InstanceHandle instance = InstanceHandle.Create(rendererIndex);
int instanceIndex = renderWorld.HandleToIndex(instance);
return renderWorld.localToWorldIsFlippedBits.Get(instanceIndex);
}
// Keep in sync with isMeshLodVisible from DrawCommandOutputPerBatch
private bool IsMeshLodVisible(int batchLodLevel, int rendererIndex, bool supportsCrossFade)
{
if (batchLodLevel < 0)
return true;
var meshLodLevel = rendererMeshLodSettings[rendererIndex];
var instanceLodLevel = meshLodLevel & ~CullingJob.k_MeshLodCrossfadeBits;
if (batchLodLevel == instanceLodLevel)
return true;
if (!supportsCrossFade)
return false;
var crossfadeBits = (meshLodLevel & CullingJob.k_MeshLodCrossfadeBits);
if (crossfadeBits == 0)
return false;
// This sets sign to 1 if the 8th bit (e.g. k_MeshCrossfadeSignBit is set), and -1 otherwise.
var sign = (int)(crossfadeBits - CullingJob.k_MeshLodCrossfadeSignBit) >> 6;
return batchLodLevel == instanceLodLevel + sign;
}
static int GetPrimitiveCount(int indexCount, MeshTopology topology, bool nativeQuads)
{
switch (topology)
{
case MeshTopology.Triangles: return indexCount / 3;
case MeshTopology.Quads: return nativeQuads ? (indexCount / 4) : (indexCount / 4 * 2);
case MeshTopology.Lines: return indexCount / 2;
case MeshTopology.LineStrip: return (indexCount >= 1) ? (indexCount - 1) : 0;
case MeshTopology.Points: return indexCount;
default: Debug.Assert(false, "unknown primitive type"); return 0;
}
}
public void Execute(int batchIndex)
{
// figure out how many combinations of views/features we need to partition by
int configCount = binningConfig.visibilityConfigCount;
// allocate space to keep track of the number of instances per config
Span<int> visibleCountPerConfig = stackalloc int[configCount];
for (int i = 0; i < configCount; ++i)
visibleCountPerConfig[i] = 0;
// and space to keep track of which configs have any instances
int configMaskCount = (configCount + 63)/64;
Span<ulong> configUsedMasks = stackalloc ulong[configMaskCount];
for (int i = 0; i < configMaskCount; ++i)
configUsedMasks[i] = 0;
// loop over all instances within this batch
var drawBatch = drawBatches[batchIndex];
var instanceCount = drawBatch.instanceCount;
var instanceOffset = drawBatch.instanceOffset;
var supportsCrossFade = (drawBatch.key.flags & BatchDrawCommandFlags.LODCrossFadeKeyword) != 0;
for (int i = 0; i < instanceCount; ++i)
{
var rendererIndex = drawInstanceIndices[instanceOffset + i];
bool isFlipped = IsInstanceFlipped(rendererIndex);
int visibilityMask = rendererVisibilityMasks[rendererIndex];
bool isVisible = (visibilityMask != 0);
if (!isVisible)
continue;
if (!IsMeshLodVisible(drawBatch.key.activeMeshLod, rendererIndex, supportsCrossFade))
continue;
int configIndex = (int)(visibilityMask << 1) | (isFlipped ? 1 : 0);
Assert.IsTrue(configIndex < configCount);
visibleCountPerConfig[configIndex]++;
configUsedMasks[configIndex >> 6] |= 1ul << (configIndex & 0x3f);
}
// allocate and store the non-empty configs as bins
int binCount = 0;
for (int i = 0; i < configMaskCount; ++i)
binCount += math.countbits(configUsedMasks[i]);
int allocOffsetStart = 0;
if (binCount > 0)
{
Span<int> drawCommandCountPerView = stackalloc int[binningConfig.viewCount];
Span<int> visibleCountPerView = stackalloc int[binningConfig.viewCount];
for (int i = 0; i < binningConfig.viewCount; ++i)
{
drawCommandCountPerView[i] = 0;
visibleCountPerView[i] = 0;
}
bool countVisibilityStats = (debugCounterIndexBase >= 0);
int shiftForVisibilityMask = 1 + (binningConfig.supportsMotionCheck ? 1 : 0) + (binningConfig.supportsCrossFade ? 1 : 0);
int* allocCounter = (int*)binAllocCounter.GetUnsafePtr();
int allocOffsetEnd = Interlocked.Add(ref UnsafeUtility.AsRef<int>(allocCounter), binCount);
allocOffsetStart = allocOffsetEnd - binCount;
int allocOffset = allocOffsetStart;
for (int i = 0; i < configMaskCount; ++i)
{
UInt64 configRemainMask = configUsedMasks[i];
while (configRemainMask != 0)
{
var bitPos = math.tzcnt(configRemainMask);
configRemainMask ^= 1ul << bitPos;
int configIndex = 64*i + bitPos;
int visibleCount = visibleCountPerConfig[configIndex];
Assert.IsTrue(visibleCount > 0);
binConfigIndices[allocOffset] = (short)configIndex;
binVisibleInstanceCounts[allocOffset] = visibleCount;
allocOffset++;
int visibilityMask = countVisibilityStats ? (configIndex >> shiftForVisibilityMask) : 0;
while (visibilityMask != 0)
{
var viewIndex = math.tzcnt(visibilityMask);
visibilityMask ^= 1 << viewIndex;
drawCommandCountPerView[viewIndex] += 1;
visibleCountPerView[viewIndex] += visibleCount;
}
}
}
Assert.IsTrue(allocOffset == allocOffsetEnd);
if (countVisibilityStats)
{
for (int viewIndex = 0; viewIndex < binningConfig.viewCount; ++viewIndex)
{
int* counterPtr = (int*)splitDebugCounters.GetUnsafePtr() + (debugCounterIndexBase + viewIndex) * (int)InstanceCullerSplitDebugCounter.Count;
int drawCommandCount = drawCommandCountPerView[viewIndex];
if (drawCommandCount > 0)
Interlocked.Add(ref UnsafeUtility.AsRef<int>(counterPtr + (int)InstanceCullerSplitDebugCounter.DrawCommands), drawCommandCount);
int visibleCount = visibleCountPerView[viewIndex];
if (visibleCount > 0)
{
int primitiveCount = GetPrimitiveCount((int)drawBatch.indexCount, drawBatch.topology, false);
Interlocked.Add(ref UnsafeUtility.AsRef<int>(counterPtr + (int)InstanceCullerSplitDebugCounter.VisibleInstances), visibleCount);
Interlocked.Add(ref UnsafeUtility.AsRef<int>(counterPtr + (int)InstanceCullerSplitDebugCounter.VisiblePrimitives), visibleCount * primitiveCount);
}
}
}
}
batchBinAllocOffsets[batchIndex] = allocOffsetStart;
batchBinCounts[batchIndex] = binCount;
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal unsafe struct PrefixSumDrawsAndInstances : IJob
{
[ReadOnly] public NativeList<DrawRange> drawRanges;
[ReadOnly] public NativeArray<int> drawBatchIndices;
[ReadOnly] public NativeArray<int> batchBinAllocOffsets;
[ReadOnly] public NativeArray<int> batchBinCounts;
[ReadOnly] public NativeArray<int> binVisibleInstanceCounts;
[NativeDisableContainerSafetyRestriction, NoAlias] [WriteOnly] public NativeArray<int> batchDrawCommandOffsets;
[NativeDisableContainerSafetyRestriction, NoAlias] [WriteOnly] public NativeArray<int> binVisibleInstanceOffsets;
[NativeDisableUnsafePtrRestriction] public NativeArray<BatchCullingOutputDrawCommands> cullingOutput;
[ReadOnly] public IndirectBufferLimits indirectBufferLimits;
[NativeDisableContainerSafetyRestriction, NoAlias] public NativeArray<IndirectBufferAllocInfo> indirectBufferAllocInfo;
[NativeDisableContainerSafetyRestriction, NoAlias] public NativeArray<int> indirectAllocationCounters;
unsafe public void Execute()
{
BatchCullingOutputDrawCommands output = cullingOutput[0];
bool allowIndirect = indirectBufferLimits.maxInstanceCount > 0;
int outRangeIndex;
int outDirectCommandIndex;
int outDirectVisibleInstanceIndex;
int outIndirectCommandIndex;
int outIndirectVisibleInstanceIndex;
for (;;)
{
// reset counters
outRangeIndex = 0;
outDirectCommandIndex = 0;
outDirectVisibleInstanceIndex = 0;
outIndirectCommandIndex = 0;
outIndirectVisibleInstanceIndex = 0;
for (int rangeIndex = 0; rangeIndex < drawRanges.Length; ++rangeIndex)
{
var drawRangeInfo = drawRanges[rangeIndex];
bool isIndirect = allowIndirect && drawRangeInfo.key.supportsIndirect;
int rangeDrawCommandCount = 0;
int rangeDrawCommandOffset = isIndirect ? outIndirectCommandIndex : outDirectCommandIndex;
for (int drawIndexInRange = 0; drawIndexInRange < drawRangeInfo.drawCount; ++drawIndexInRange)
{
var batchIndex = drawBatchIndices[drawRangeInfo.drawOffset + drawIndexInRange];
var binAllocOffset = batchBinAllocOffsets[batchIndex];
var binCount = batchBinCounts[batchIndex];
if (isIndirect)
{
batchDrawCommandOffsets[batchIndex] = outIndirectCommandIndex;
outIndirectCommandIndex += binCount;
}
else
{
batchDrawCommandOffsets[batchIndex] = outDirectCommandIndex;
outDirectCommandIndex += binCount;
}
rangeDrawCommandCount += binCount;
for (int binIndexInBatch = 0; binIndexInBatch < binCount; ++binIndexInBatch)
{
var binIndex = binAllocOffset + binIndexInBatch;
if (isIndirect)
{
binVisibleInstanceOffsets[binIndex] = outIndirectVisibleInstanceIndex;
outIndirectVisibleInstanceIndex += binVisibleInstanceCounts[binIndex];
}
else
{
binVisibleInstanceOffsets[binIndex] = outDirectVisibleInstanceIndex;
outDirectVisibleInstanceIndex += binVisibleInstanceCounts[binIndex];
}
}
}
if (rangeDrawCommandCount != 0)
{
#if DEBUG
if (outRangeIndex >= output.drawRangeCount)
throw new Exception("Exceeding draw range count");
#endif
var rangeKey = drawRangeInfo.key;
output.drawRanges[outRangeIndex] = new BatchDrawRange
{
drawCommandsBegin = (uint)rangeDrawCommandOffset,
drawCommandsCount = (uint)rangeDrawCommandCount,
drawCommandsType = isIndirect ? BatchDrawCommandType.Indirect : BatchDrawCommandType.Direct,
filterSettings = new BatchFilterSettings
{
renderingLayerMask = rangeKey.renderingLayerMask,
rendererPriority = rangeKey.rendererPriority,
layer = rangeKey.layer,
batchLayer = isIndirect ? BatchLayer.InstanceCullingIndirect : BatchLayer.InstanceCullingDirect,
motionMode = rangeKey.motionMode,
shadowCastingMode = rangeKey.shadowCastingMode,
receiveShadows = true,
staticShadowCaster = rangeKey.staticShadowCaster,
allDepthSorted = false,
}
};
outRangeIndex++;
}
}
output.drawRangeCount = outRangeIndex; // trim to the number of written ranges
// try to allocate buffer space for indirect
bool isValid = true;
if (allowIndirect)
{
int* allocCounters = (int*)indirectAllocationCounters.GetUnsafePtr();
var allocInfo = new IndirectBufferAllocInfo();
allocInfo.drawCount = outIndirectCommandIndex;
allocInfo.instanceCount = outIndirectVisibleInstanceIndex;
int drawAllocCount = allocInfo.drawCount;
int drawAllocEnd = Interlocked.Add(ref UnsafeUtility.AsRef<int>(allocCounters + (int)IndirectAllocator.NextDrawIndex), drawAllocCount);
allocInfo.drawAllocIndex = drawAllocEnd - drawAllocCount;
int instanceAllocEnd = Interlocked.Add(ref UnsafeUtility.AsRef<int>(allocCounters + (int)IndirectAllocator.NextInstanceIndex), allocInfo.instanceCount);
allocInfo.instanceAllocIndex = instanceAllocEnd - allocInfo.instanceCount;
if (!allocInfo.IsWithinLimits(indirectBufferLimits))
{
allocInfo = new IndirectBufferAllocInfo();
isValid = false;
}
indirectBufferAllocInfo[0] = allocInfo;
}
if (isValid)
break;
// out of indirect memory, reset counters and try again without indirect
//Debug.Log("Out of indirect buffer space: falling back to direct draws for this frame!");
allowIndirect = false;
}
if (outDirectCommandIndex != 0)
{
output.drawCommandCount = outDirectCommandIndex;
output.drawCommands = MemoryUtilities.Malloc<BatchDrawCommand>(outDirectCommandIndex, Allocator.TempJob);
output.visibleInstanceCount = outDirectVisibleInstanceIndex;
output.visibleInstances = MemoryUtilities.Malloc<int>(outDirectVisibleInstanceIndex, Allocator.TempJob);
}
if (outIndirectCommandIndex != 0)
{
output.indirectDrawCommandCount = outIndirectCommandIndex;
output.indirectDrawCommands = MemoryUtilities.Malloc<BatchDrawCommandIndirect>(outIndirectCommandIndex, Allocator.TempJob);
}
int totalCommandCount = outDirectCommandIndex + outIndirectCommandIndex;
output.instanceSortingPositions = MemoryUtilities.Malloc<float>(3 * totalCommandCount, Allocator.TempJob);
cullingOutput[0] = output;
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal unsafe struct DrawCommandOutputPerBatch : IJobParallelFor
{
[ReadOnly] public BinningConfig binningConfig;
[ReadOnly] public NativeParallelHashMap<GPUArchetypeHandle, BatchID> batchIDs;
[ReadOnly] public GPUInstanceDataBuffer.ReadOnly instanceDataBuffer;
[ReadOnly] public NativeList<DrawBatch> drawBatches;
[ReadOnly] public NativeArray<int> drawInstanceIndices;
[ReadOnly] public RenderWorld renderWorld;
[ReadOnly] public NativeArray<byte> rendererVisibilityMasks;
[ReadOnly] public NativeArray<byte> rendererMeshLodSettings;
[ReadOnly] public NativeArray<byte> rendererCrossFadeValues;
[ReadOnly] [DeallocateOnJobCompletion] public NativeArray<int> batchBinAllocOffsets;
[ReadOnly] [DeallocateOnJobCompletion] public NativeArray<int> batchBinCounts;
[ReadOnly] [DeallocateOnJobCompletion] public NativeArray<int> batchDrawCommandOffsets;
[ReadOnly] [DeallocateOnJobCompletion] public NativeArray<short> binConfigIndices;
[ReadOnly] [DeallocateOnJobCompletion] public NativeArray<int> binVisibleInstanceOffsets;
[ReadOnly] [DeallocateOnJobCompletion] public NativeArray<int> binVisibleInstanceCounts;
[ReadOnly] public NativeArray<BatchCullingOutputDrawCommands> cullingOutput;
[ReadOnly] public IndirectBufferLimits indirectBufferLimits;
[ReadOnly] public GraphicsBufferHandle visibleInstancesBufferHandle;
[ReadOnly] public GraphicsBufferHandle indirectArgsBufferHandle;
[NativeDisableContainerSafetyRestriction, NoAlias] public NativeArray<IndirectBufferAllocInfo> indirectBufferAllocInfo;
[NativeDisableContainerSafetyRestriction, NoAlias] public NativeArray<IndirectDrawInfo> indirectDrawInfoGlobalArray;
[NativeDisableContainerSafetyRestriction, NoAlias] public NativeArray<IndirectInstanceInfo> indirectInstanceInfoGlobalArray;
int EncodeGPUInstanceIndexAndCrossFade(int rendererIndex, bool negateCrossFade)
{
int instanceIndex = renderWorld.HandleToIndex(InstanceHandle.Create(rendererIndex));
InstanceGPUHandle gpuHandle = renderWorld.gpuHandles[instanceIndex];
GPUInstanceIndex gpuIndex = instanceDataBuffer.InstanceGPUHandleToGPUIndex(gpuHandle);
int crossFadeValue = rendererCrossFadeValues[rendererIndex];
if (crossFadeValue == CullingJob.k_LODFadeOff)
return gpuIndex.index;
crossFadeValue -= (int)CullingJob.k_LODFadeZeroPacked;
if (negateCrossFade)
crossFadeValue = -crossFadeValue;
return gpuIndex.index | (crossFadeValue << 24);
}
bool IsInstanceFlipped(int rendererIndex)
{
InstanceHandle instance = InstanceHandle.Create(rendererIndex);
int instanceIndex = renderWorld.HandleToIndex(instance);
return renderWorld.localToWorldIsFlippedBits.Get(instanceIndex);
}
// This must be kept in sync with IsMeshLodVisible from binning pass
private bool IsMeshLodVisible(int batchLodLevel, int rendererIndex, bool supportsCrossFade, ref bool negateCrossfade)
{
if (batchLodLevel < 0)
return true;
var meshLodSetting = rendererMeshLodSettings[rendererIndex];
var instanceLodLevel = meshLodSetting & ~CullingJob.k_MeshLodCrossfadeBits;
if (batchLodLevel == instanceLodLevel)
return true;
if (!supportsCrossFade)
return false;
var crossfadeBits = (meshLodSetting & CullingJob.k_MeshLodCrossfadeBits);
if (crossfadeBits == 0)
return false;
// This sets sign to 1 if the 8th bit (e.g. k_MeshLodCrossfadeSignBit is set), and -1 otherwise.
var sign = (int)(crossfadeBits - CullingJob.k_MeshLodCrossfadeSignBit) >> 6;
negateCrossfade = true;
return batchLodLevel == instanceLodLevel + sign;
}
unsafe public void Execute(int batchIndex)
{
DrawBatch drawBatch = drawBatches[batchIndex];
var binCount = batchBinCounts[batchIndex];
if (binCount == 0)
return;
BatchCullingOutputDrawCommands output = cullingOutput[0];
IndirectBufferAllocInfo indirectAllocInfo = new IndirectBufferAllocInfo();
if (indirectBufferLimits.maxDrawCount > 0)
indirectAllocInfo = indirectBufferAllocInfo[0];
bool allowIndirect = !indirectAllocInfo.IsEmpty();
bool isIndirect = allowIndirect && drawBatch.key.range.supportsIndirect;
// figure out how many combinations of views/features we need to partition by
int configCount = binningConfig.visibilityConfigCount;
// allocate storage for the instance offsets, set to zero
Span<int> instanceOffsetPerConfig = stackalloc int[configCount];
for (int i = 0; i < configCount; ++i)
instanceOffsetPerConfig[i] = 0;
// allocate storage to be able to look up the draw index per instance (by config)
Span<int> drawCommandOffsetPerConfig = stackalloc int[configCount];
// write the draw commands, scatter the allocated offsets to our storage