-
Notifications
You must be signed in to change notification settings - Fork 822
/
Copy pathGPUResidentDrawer.cs
1021 lines (834 loc) · 43.5 KB
/
GPUResidentDrawer.cs
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
#define GPU_RESIDENT_DRAWER_ALLOW_FORCE_ON
using System;
using System.Collections.Generic;
using Unity.Collections;
using UnityEngine.Assertions;
using UnityEngine.LowLevel;
using UnityEngine.PlayerLoop;
using UnityEngine.Profiling;
using UnityEngine.SceneManagement;
using static UnityEngine.ObjectDispatcher;
using Unity.Jobs;
using static UnityEngine.Rendering.RenderersParameters;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine.Rendering.RenderGraphModule;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Burst;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Rendering;
#endif
namespace UnityEngine.Rendering
{
/// <summary>
/// Static utility class for updating data post cull in begin camera rendering
/// </summary>
public partial class GPUResidentDrawer
{
internal static GPUResidentDrawer instance { get => s_Instance; }
private static GPUResidentDrawer s_Instance = null;
////////////////////////////////////////
// Public API for rendering pipelines //
////////////////////////////////////////
#region Public API
/// <summary>
/// Utility function to test if instance occlusion culling is enabled
/// </summary>
/// <returns>True if instance occlusion culling is enabled</returns>
public static bool IsInstanceOcclusionCullingEnabled()
{
if (s_Instance == null)
return false;
if (s_Instance.settings.mode != GPUResidentDrawerMode.InstancedDrawing)
return false;
if (s_Instance.settings.enableOcclusionCulling)
return true;
return false;
}
/// <summary>
/// Utility function for updating data post cull in begin camera rendering
/// </summary>
/// <param name="context">
/// Context containing the data to be set
/// </param>
public static void PostCullBeginCameraRendering(RenderRequestBatcherContext context)
{
s_Instance?.batcher.PostCullBeginCameraRendering(context);
}
/// <summary>
/// Utility function for updating probe data after global ambient probe is set up
/// </summary>
public static void OnSetupAmbientProbe()
{
s_Instance?.batcher.OnSetupAmbientProbe();
}
/// <summary>
/// Utility function to run an occlusion test in compute to update indirect draws.
/// This function will dispatch compute shaders to run the given occlusion test and
/// update all indirect draws in the culling output for the given view.
/// The next time a renderer list that uses this culling output is drawn, these
/// indirect draw commands will contain only the instances that passed the given
/// occlusion test.
/// </summary>
/// <param name="renderGraph">Render graph that will have a compute pass added.</param>
/// <param name="settings">The view to update and occlusion test to use.</param>
/// <param name="subviewOcclusionTests">Specifies the occluder subviews to use with each culling split index.</param>
public static void InstanceOcclusionTest(RenderGraph renderGraph, in OcclusionCullingSettings settings, ReadOnlySpan<SubviewOcclusionTest> subviewOcclusionTests)
{
s_Instance?.batcher.InstanceOcclusionTest(renderGraph, settings, subviewOcclusionTests);
}
/// <summary>
/// Utility function used to update occluders using a depth buffer.
/// This function will dispatch compute shaders to read the given depth buffer
/// and build a mip pyramid of closest depths for use during occlusion culling.
/// The next time an occlusion test is issed for this view, instances will be
/// tested against the updated occluders.
/// </summary>
/// <param name="renderGraph">Render graph that will have a compute pass added.</param>
/// <param name="occluderParameters">Parameter to specify the view and depth buffer to read.</param>
/// <param name="occluderSubviewUpdates">Specifies which occluder subviews to update from slices of the input depth buffer.</param>
public static void UpdateInstanceOccluders(RenderGraph renderGraph, in OccluderParameters occluderParameters, ReadOnlySpan<OccluderSubviewUpdate> occluderSubviewUpdates)
{
s_Instance?.batcher.UpdateInstanceOccluders(renderGraph, occluderParameters, occluderSubviewUpdates);
}
/// <summary>
/// Enable or disable GPUResidentDrawer based on the project settings.
/// We call this every frame because GPUResidentDrawer can be enabled/disabled by the settings outside the render pipeline asset.
/// </summary>
public static void ReinitializeIfNeeded()
{
#if UNITY_EDITOR
if (!IsForcedOnViaCommandLine() && (IsProjectSupported() != IsEnabled()))
{
Reinitialize();
}
#endif
}
#endregion
#region Public Debug API
/// <summary>
/// Utility function to render an occlusion test heatmap debug overlay.
/// </summary>
/// <param name="renderGraph">Render graph that will have a compute pass added.</param>
/// <param name="debugSettings">The rendering debugger debug settings to read parameters from.</param>
/// <param name="viewInstanceID">The instance ID of the camera using a GPU occlusion test.</param>
/// <param name="colorBuffer">The color buffer to render the overlay on.</param>
public static void RenderDebugOcclusionTestOverlay(RenderGraph renderGraph, DebugDisplayGPUResidentDrawer debugSettings, int viewInstanceID, TextureHandle colorBuffer)
{
s_Instance?.batcher.occlusionCullingCommon.RenderDebugOcclusionTestOverlay(renderGraph, debugSettings, viewInstanceID, colorBuffer);
}
/// <summary>
/// Utility function visualise the occluder pyramid in a debug overlay.
/// </summary>
/// <param name="renderGraph">Render graph that will have a compute pass added.</param>
/// <param name="debugSettings">The rendering debugger debug settings to read parameters from.</param>
/// <param name="screenPos">The screen position to render the overlay at.</param>
/// <param name="maxHeight">The maximum screen height of the overlay.</param>
/// <param name="colorBuffer">The color buffer to render the overlay on.</param>
public static void RenderDebugOccluderOverlay(RenderGraph renderGraph, DebugDisplayGPUResidentDrawer debugSettings, Vector2 screenPos, float maxHeight, TextureHandle colorBuffer)
{
s_Instance?.batcher.occlusionCullingCommon.RenderDebugOccluderOverlay(renderGraph, debugSettings, screenPos, maxHeight, colorBuffer);
}
#endregion
internal static DebugRendererBatcherStats GetDebugStats()
{
return s_Instance?.m_BatchersContext.debugStats;
}
private void InsertIntoPlayerLoop()
{
var rootLoop = LowLevel.PlayerLoop.GetCurrentPlayerLoop();
bool isAdded = false;
for (var i = 0; i < rootLoop.subSystemList.Length; i++)
{
var subSystem = rootLoop.subSystemList[i];
// We have to update inside the PostLateUpdate systems, because we have to be able to get previous matrices from renderers.
// Previous matrices are updated by renderer managers on UpdateAllRenderers which is part of PostLateUpdate.
if (!isAdded && subSystem.type == typeof(PostLateUpdate))
{
var subSubSystems = new List<PlayerLoopSystem>();
foreach (var subSubSystem in subSystem.subSystemList)
{
if (subSubSystem.type == typeof(PostLateUpdate.FinishFrameRendering))
{
PlayerLoopSystem s = default;
s.updateDelegate += PostPostLateUpdateStatic;
s.type = GetType();
subSubSystems.Add(s);
isAdded = true;
}
subSubSystems.Add(subSubSystem);
}
subSystem.subSystemList = subSubSystems.ToArray();
rootLoop.subSystemList[i] = subSystem;
}
}
LowLevel.PlayerLoop.SetPlayerLoop(rootLoop);
}
private void RemoveFromPlayerLoop()
{
var rootLoop = LowLevel.PlayerLoop.GetCurrentPlayerLoop();
for (int i = 0; i < rootLoop.subSystemList.Length; i++)
{
var subsystem = rootLoop.subSystemList[i];
if (subsystem.type != typeof(PostLateUpdate))
continue;
var newList = new List<PlayerLoopSystem>();
foreach (var subSubSystem in subsystem.subSystemList)
{
if (subSubSystem.type != GetType())
newList.Add(subSubSystem);
}
subsystem.subSystemList = newList.ToArray();
rootLoop.subSystemList[i] = subsystem;
}
LowLevel.PlayerLoop.SetPlayerLoop(rootLoop);
}
#if UNITY_EDITOR
private static void OnAssemblyReload()
{
if (s_Instance is not null)
s_Instance.Dispose();
}
#endif
internal static bool IsEnabled()
{
return s_Instance is not null;
}
internal static GPUResidentDrawerSettings GetGlobalSettingsFromRPAsset()
{
var renderPipelineAsset = GraphicsSettings.currentRenderPipeline;
if (renderPipelineAsset is not IGPUResidentRenderPipeline mbAsset)
return new GPUResidentDrawerSettings();
var settings = mbAsset.gpuResidentDrawerSettings;
if (IsForcedOnViaCommandLine())
settings.mode = GPUResidentDrawerMode.InstancedDrawing;
if (IsOcclusionForcedOnViaCommandLine())
settings.enableOcclusionCulling = true;
return settings;
}
/// <summary>
/// Is GRD forced on via the command line via -force-gpuresidentdrawer. Editor only.
/// </summary>
/// <returns>true if forced on</returns>
private static bool IsForcedOnViaCommandLine()
{
#if UNITY_EDITOR
return s_IsForcedOnViaCommandLine;
#else
return false;
#endif
}
/// <summary>
/// Is occlusion culling forced on via the command line via -force-gpuocclusion. Editor only.
/// </summary>
/// <returns>true if forced on</returns>
private static bool IsOcclusionForcedOnViaCommandLine()
{
#if UNITY_EDITOR
return s_IsOcclusionForcedOnViaCommandLine;
#else
return false;
#endif
}
internal static void Reinitialize()
{
var settings = GetGlobalSettingsFromRPAsset();
// When compiling in the editor, we include a try catch block around our initialization logic to avoid leaving the editor window in a broken state if something goes wrong.
// We can probably remove this in the future once the edit mode functionality stabilizes, but for now it's safest to have a fallback.
#if UNITY_EDITOR
try
#endif
{
Recreate(settings);
}
#if UNITY_EDITOR
catch (Exception exception)
{
Debug.LogError($"The GPU Resident Drawer encountered an error during initialization. The standard SRP path will be used instead. [Error: {exception.Message}]");
Debug.LogError($"GPU Resident drawer stack trace: {exception.StackTrace}");
CleanUp();
}
#endif
}
private static void CleanUp()
{
if (s_Instance == null)
return;
s_Instance.Dispose();
s_Instance = null;
}
private static void Recreate(GPUResidentDrawerSettings settings)
{
CleanUp();
if (IsGPUResidentDrawerSupportedBySRP(settings, out var message, out var severity))
{
s_Instance = new GPUResidentDrawer(settings, 4096, 0);
}
else
{
LogMessage(message, severity);
}
}
IntPtr m_ContextIntPtr = IntPtr.Zero;
internal GPUResidentBatcher batcher { get => m_Batcher; }
internal GPUResidentDrawerSettings settings { get => m_Settings; }
private GPUResidentDrawerSettings m_Settings;
private GPUDrivenProcessor m_GPUDrivenProcessor = null;
private RenderersBatchersContext m_BatchersContext = null;
private GPUResidentBatcher m_Batcher = null;
private ObjectDispatcher m_Dispatcher;
#if UNITY_EDITOR
private static readonly bool s_IsForcedOnViaCommandLine;
private static readonly bool s_IsOcclusionForcedOnViaCommandLine;
private NativeList<int> m_FrameCameraIDs;
private bool m_FrameUpdateNeeded = false;
private bool m_IsSelectionDirty;
static GPUResidentDrawer()
{
Lightmapping.bakeCompleted += Reinitialize;
#if GPU_RESIDENT_DRAWER_ALLOW_FORCE_ON
foreach (var arg in Environment.GetCommandLineArgs())
{
if (arg.Equals("-force-gpuresidentdrawer", StringComparison.InvariantCultureIgnoreCase))
{
Debug.Log("GPU Resident Drawer forced on via commandline");
s_IsForcedOnViaCommandLine = true;
}
if (arg.Equals("-force-gpuocclusion", StringComparison.InvariantCultureIgnoreCase))
{
Debug.Log("GPU occlusion culling forced on via commandline");
s_IsOcclusionForcedOnViaCommandLine = true;
}
}
#endif
}
#endif
private GPUResidentDrawer(GPUResidentDrawerSettings settings, int maxInstanceCount, int maxTreeInstanceCount)
{
var resources = GraphicsSettings.GetRenderPipelineSettings<GPUResidentDrawerResources>();
var renderPipelineAsset = GraphicsSettings.currentRenderPipeline;
var mbAsset = renderPipelineAsset as IGPUResidentRenderPipeline;
Debug.Assert(mbAsset != null, "No compatible Render Pipeline found");
Assert.IsFalse(settings.mode == GPUResidentDrawerMode.Disabled);
m_Settings = settings;
var rbcDesc = RenderersBatchersContextDesc.NewDefault();
rbcDesc.instanceNumInfo = new InstanceNumInfo(meshRendererNum: maxInstanceCount, speedTreeNum: maxTreeInstanceCount);
rbcDesc.supportDitheringCrossFade = settings.supportDitheringCrossFade;
rbcDesc.smallMeshScreenPercentage = settings.smallMeshScreenPercentage;
rbcDesc.enableBoundingSpheresInstanceData = settings.enableOcclusionCulling;
rbcDesc.enableCullerDebugStats = true; // for now, always allow the possibility of reading counter stats from the cullers.
var instanceCullingBatcherDesc = InstanceCullingBatcherDesc.NewDefault();
#if UNITY_EDITOR
instanceCullingBatcherDesc.brgPicking = settings.pickingShader;
instanceCullingBatcherDesc.brgLoading = settings.loadingShader;
instanceCullingBatcherDesc.brgError = settings.errorShader;
#endif
m_GPUDrivenProcessor = new GPUDrivenProcessor();
m_BatchersContext = new RenderersBatchersContext(rbcDesc, m_GPUDrivenProcessor, resources);
m_Batcher = new GPUResidentBatcher(
m_BatchersContext,
instanceCullingBatcherDesc,
m_GPUDrivenProcessor);
m_Dispatcher = new ObjectDispatcher();
m_Dispatcher.EnableTypeTracking<LODGroup>(TypeTrackingFlags.SceneObjects);
m_Dispatcher.EnableTypeTracking<Mesh>();
m_Dispatcher.EnableTypeTracking<Material>();
m_Dispatcher.EnableTransformTracking<LODGroup>(TransformTrackingType.GlobalTRS);
m_Dispatcher.EnableTypeTracking<MeshRenderer>(TypeTrackingFlags.SceneObjects);
m_Dispatcher.EnableTransformTracking<MeshRenderer>(TransformTrackingType.GlobalTRS);
#if UNITY_EDITOR
AssemblyReloadEvents.beforeAssemblyReload += OnAssemblyReload;
m_FrameCameraIDs = new NativeList<int>(1, Allocator.Persistent);
m_IsSelectionDirty = true; // Force at least one selection update
#endif
SceneManager.sceneLoaded += OnSceneLoaded;
RenderPipelineManager.beginContextRendering += OnBeginContextRendering;
RenderPipelineManager.endContextRendering += OnEndContextRendering;
RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering += OnEndCameraRendering;
#if UNITY_EDITOR
Selection.selectionChanged += OnSelectionChanged;
#endif
// GPU Resident Drawer only supports legacy lightmap binding.
// Accordingly, we set the keyword globally across all shaders.
const string useLegacyLightmapsKeyword = "USE_LEGACY_LIGHTMAPS";
Shader.EnableKeyword(useLegacyLightmapsKeyword);
InsertIntoPlayerLoop();
}
private void Dispose()
{
Assert.IsNotNull(s_Instance);
#if UNITY_EDITOR
AssemblyReloadEvents.beforeAssemblyReload -= OnAssemblyReload;
if (m_FrameCameraIDs.IsCreated)
m_FrameCameraIDs.Dispose();
#endif
SceneManager.sceneLoaded -= OnSceneLoaded;
// Note: Those RenderPipelineManager callbacks do not run when using built-in editor debug views such as lightmap, shadowmask etc
RenderPipelineManager.beginContextRendering -= OnBeginContextRendering;
RenderPipelineManager.endContextRendering -= OnEndContextRendering;
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering -= OnEndCameraRendering;
#if UNITY_EDITOR
Selection.selectionChanged -= OnSelectionChanged;
#endif
RemoveFromPlayerLoop();
const string useLegacyLightmapsKeyword = "USE_LEGACY_LIGHTMAPS";
Shader.DisableKeyword(useLegacyLightmapsKeyword);
m_Dispatcher.Dispose();
m_Dispatcher = null;
s_Instance = null;
m_Batcher?.Dispose();
m_BatchersContext.Dispose();
m_GPUDrivenProcessor.Dispose();
m_ContextIntPtr = IntPtr.Zero;
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
// Loaded scene might contain light probes that would affect existing objects. Hence we have to update all probes data.
if(mode == LoadSceneMode.Additive)
m_BatchersContext.UpdateAmbientProbeAndGpuBuffer(forceUpdate: true);
}
private static void PostPostLateUpdateStatic()
{
s_Instance?.PostPostLateUpdate();
}
private void OnBeginContextRendering(ScriptableRenderContext context, List<Camera> cameras)
{
if (s_Instance is null)
return;
// This logic ensures that EditorFrameUpdate is not called more than once after calling BeginContextRendering, unless EndContextRendering has also been called.
if (m_ContextIntPtr == IntPtr.Zero)
{
m_ContextIntPtr = context.Internal_GetPtr();
#if UNITY_EDITOR
EditorFrameUpdate(cameras);
#endif
m_Batcher.OnBeginContextRendering();
}
}
#if UNITY_EDITOR
// If running in the editor the player loop might not run
// In order to still have a single frame update we keep track of the camera ids
// A frame update happens in case the first camera is rendered again
// Note: This doesn't run when using built-in debug views such as lightmaps, shadowmask and etc
private void EditorFrameUpdate(List<Camera> cameras)
{
bool newFrame = false;
foreach (Camera camera in cameras)
{
int instanceID = camera.GetInstanceID();
if (m_FrameCameraIDs.Length == 0 || m_FrameCameraIDs.Contains(instanceID))
{
newFrame = true;
m_FrameCameraIDs.Clear();
}
m_FrameCameraIDs.Add(instanceID);
}
if (newFrame)
{
if (m_FrameUpdateNeeded)
m_Batcher.UpdateFrame();
else
m_FrameUpdateNeeded = true;
}
}
private void OnSelectionChanged()
{
m_IsSelectionDirty = true;
}
private void UpdateSelection()
{
Profiler.BeginSample("GPUResidentDrawer.UpdateSelection");
Object[] renderers = Selection.GetFiltered(typeof(MeshRenderer), SelectionMode.Deep);
var rendererIDs = new NativeArray<int>(renderers.Length, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
for (int i = 0; i < renderers.Length; ++i)
rendererIDs[i] = renderers[i] ? renderers[i].GetInstanceID() : 0;
m_Batcher.UpdateSelectedRenderers(rendererIDs);
rendererIDs.Dispose();
Profiler.EndSample();
}
#endif
private void OnEndContextRendering(ScriptableRenderContext context, List<Camera> cameras)
{
if (s_Instance is null)
return;
if (m_ContextIntPtr == context.Internal_GetPtr())
{
m_ContextIntPtr = IntPtr.Zero;
m_Batcher.OnEndContextRendering();
}
}
private void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
{
m_Batcher.OnBeginCameraRendering(camera);
}
private void OnEndCameraRendering(ScriptableRenderContext context, Camera camera)
{
m_Batcher.OnEndCameraRendering(camera);
}
private void PostPostLateUpdate()
{
m_BatchersContext.UpdateAmbientProbeAndGpuBuffer(forceUpdate: false);
Profiler.BeginSample("GPUResidentDrawer.DispatchChanges");
var lodGroupTransformData = m_Dispatcher.GetTransformChangesAndClear<LODGroup>(TransformTrackingType.GlobalTRS, Allocator.TempJob);
var lodGroupData = m_Dispatcher.GetTypeChangesAndClear<LODGroup>(Allocator.TempJob, noScriptingArray: true);
var meshDataSorted = m_Dispatcher.GetTypeChangesAndClear<Mesh>(Allocator.TempJob, sortByInstanceID: true, noScriptingArray: true);
var materialData = m_Dispatcher.GetTypeChangesAndClear<Material>(Allocator.TempJob);
var rendererData = m_Dispatcher.GetTypeChangesAndClear<MeshRenderer>(Allocator.TempJob, noScriptingArray: true);
Profiler.EndSample();
Profiler.BeginSample("GPUResidentDrawer.ClassifyMaterials");
ClassifyMaterials(materialData.changedID, out NativeList<int> unsupportedChangedMaterials,
out NativeList<int> supportedChangedMaterials,
out NativeList<GPUDrivenPackedMaterialData> supportedChangedPackedMaterialDatas, Allocator.TempJob);
Profiler.EndSample();
Profiler.BeginSample("GPUResidentDrawer.FindUnsupportedRenderers");
NativeList<int> unsupportedRenderers = FindUnsupportedRenderers(unsupportedChangedMaterials.AsArray());
Profiler.EndSample();
Profiler.BeginSample("GPUResidentDrawer.ProcessMaterials");
ProcessMaterials(materialData.destroyedID, unsupportedChangedMaterials.AsArray());
Profiler.EndSample();
Profiler.BeginSample("GPUResidentDrawer.ProcessMeshes");
ProcessMeshes(meshDataSorted.destroyedID);
Profiler.EndSample();
Profiler.BeginSample("GPUResidentDrawer.ProcessLODGroups");
ProcessLODGroups(lodGroupData.changedID, lodGroupData.destroyedID, lodGroupTransformData.transformedID);
Profiler.EndSample();
Profiler.BeginSample("GPUResidentDrawer.ProcessRenderers");
ProcessRenderers(rendererData, unsupportedRenderers.AsArray());
Profiler.EndSample();
Profiler.BeginSample("GPUResidentDrawer.ProcessRendererMaterialChanges");
ProcessRendererMaterialChanges(rendererData.changedID, supportedChangedMaterials.AsArray(), supportedChangedPackedMaterialDatas.AsArray());
Profiler.EndSample();
lodGroupTransformData.Dispose();
lodGroupData.Dispose();
meshDataSorted.Dispose();
materialData.Dispose();
rendererData.Dispose();
unsupportedChangedMaterials.Dispose();
unsupportedRenderers.Dispose();
supportedChangedMaterials.Dispose();
supportedChangedPackedMaterialDatas.Dispose();
m_BatchersContext.UpdateInstanceMotions();
m_Batcher.UpdateFrame();
#if UNITY_EDITOR
if (m_IsSelectionDirty)
{
UpdateSelection();
m_IsSelectionDirty = false;
}
m_FrameUpdateNeeded = false;
#endif
}
private void ProcessMaterials(NativeArray<int> destroyedID, NativeArray<int> unsupportedMaterials)
{
if (destroyedID.Length > 0)
m_Batcher.DestroyMaterials(destroyedID);
if (unsupportedMaterials.Length > 0)
m_Batcher.DestroyMaterials(unsupportedMaterials);
}
private void ProcessMeshes(NativeArray<int> destroyedID)
{
if (destroyedID.Length == 0)
return;
var destroyedMeshInstances = new NativeList<InstanceHandle>(Allocator.TempJob);
ScheduleQueryMeshInstancesJob(destroyedID, destroyedMeshInstances).Complete();
m_Batcher.DestroyDrawInstances(destroyedMeshInstances.AsArray());
destroyedMeshInstances.Dispose();
//@ Check if we need to update instance bounds and light probe sampling positions after mesh is destroyed.
m_Batcher.DestroyMeshes(destroyedID);
}
private void ProcessLODGroups(NativeArray<int> changedID, NativeArray<int> destroyed, NativeArray<int> transformedID)
{
m_BatchersContext.DestroyLODGroups(destroyed);
m_BatchersContext.UpdateLODGroups(changedID);
m_BatchersContext.TransformLODGroups(transformedID);
}
private void ProcessRendererMaterialChanges(NativeArray<int> excludedRenderers, NativeArray<int> changedMaterials, NativeArray<GPUDrivenPackedMaterialData> changedPackedMaterialDatas)
{
if (changedMaterials.Length == 0)
return;
Profiler.BeginSample("GPUResidentDrawer.GetMaterialsWithChangedPackedMaterial");
var filteredMaterials = GetMaterialsWithChangedPackedMaterial(changedMaterials, changedPackedMaterialDatas, Allocator.TempJob);
// Make sure we update the packed material cache AFTER filtering the materials as we need to compare the packed materials
// with their previous values.
var updatePackedMaterialCacheJob = m_Batcher.SchedulePackedMaterialCacheUpdate(changedMaterials, changedPackedMaterialDatas);
Profiler.EndSample();
if (filteredMaterials.Count == 0)
{
filteredMaterials.Dispose();
updatePackedMaterialCacheJob.Complete();
return;
}
var sortedExcludedRenderers = new NativeArray<int>(excludedRenderers, Allocator.TempJob);
if (sortedExcludedRenderers.Length > 0)
{
Profiler.BeginSample("ProcessRendererMaterialChanges.Sort");
sortedExcludedRenderers.ParallelSort().Complete();
Profiler.EndSample();
}
Profiler.BeginSample("GPUResidentDrawer.FindRenderersFromMaterials");
NativeList<int> renderersWithChangedMaterials = FindRenderersFromMaterials(sortedExcludedRenderers, filteredMaterials, Allocator.TempJob);
filteredMaterials.Dispose();
Profiler.EndSample();
sortedExcludedRenderers.Dispose();
updatePackedMaterialCacheJob.Complete();
if (renderersWithChangedMaterials.Length == 0)
{
renderersWithChangedMaterials.Dispose();
return;
}
Profiler.BeginSample("GPUResidentDrawer.UpdateRenderers");
{
var materialChangedInstances = new NativeArray<InstanceHandle>(renderersWithChangedMaterials.Length, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
ScheduleQueryRendererGroupInstancesJob(renderersWithChangedMaterials.AsArray(), materialChangedInstances).Complete();
m_Batcher.DestroyDrawInstances(materialChangedInstances);
materialChangedInstances.Dispose();
m_Batcher.UpdateRenderers(renderersWithChangedMaterials.AsArray(), true);
renderersWithChangedMaterials.Dispose();
}
Profiler.EndSample();
}
private void ProcessRenderers(TypeDispatchData rendererChanges, NativeArray<int> unsupportedRenderers)
{
Profiler.BeginSample("GPUResidentDrawer.ProcessRenderers");
var changedInstances = new NativeArray<InstanceHandle>(rendererChanges.changedID.Length, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
ScheduleQueryRendererGroupInstancesJob(rendererChanges.changedID, changedInstances).Complete();
m_Batcher.DestroyDrawInstances(changedInstances);
changedInstances.Dispose();
m_Batcher.UpdateRenderers(rendererChanges.changedID);
FreeRendererGroupInstances(rendererChanges.destroyedID, unsupportedRenderers);
Profiler.EndSample();
Profiler.BeginSample("GPUResidentDrawer.TransformMeshRenderers");
var transformChanges = m_Dispatcher.GetTransformChangesAndClear<MeshRenderer>(TransformTrackingType.GlobalTRS, Allocator.TempJob);
var transformedInstances = new NativeArray<InstanceHandle>(transformChanges.transformedID.Length, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
ScheduleQueryRendererGroupInstancesJob(transformChanges.transformedID, transformedInstances).Complete();
// We can pull localToWorldMatrices directly from the renderers if we are doing update after PostLatUpdate.
// This will save us transform re computation as matrices are ready inside renderer's TransformInfo.
TransformInstances(transformedInstances, transformChanges.localToWorldMatrices);
transformedInstances.Dispose();
transformChanges.Dispose();
Profiler.EndSample();
}
private void TransformInstances(NativeArray<InstanceHandle> instances, NativeArray<Matrix4x4> localToWorldMatrices)
{
Profiler.BeginSample("GPUResidentDrawer.TransformInstances");
m_BatchersContext.UpdateInstanceTransforms(instances, localToWorldMatrices);
Profiler.EndSample();
}
private void FreeInstances(NativeArray<InstanceHandle> instances)
{
Profiler.BeginSample("GPUResidentDrawer.FreeInstances");
m_Batcher.DestroyDrawInstances(instances);
m_BatchersContext.FreeInstances(instances);
Profiler.EndSample();
}
private void FreeRendererGroupInstances(NativeArray<int> rendererGroupIDs, NativeArray<int> unsupportedRendererGroupIDs)
{
Profiler.BeginSample("GPUResidentDrawer.FreeRendererGroupInstances");
m_Batcher.FreeRendererGroupInstances(rendererGroupIDs);
if (unsupportedRendererGroupIDs.Length > 0)
{
m_Batcher.FreeRendererGroupInstances(unsupportedRendererGroupIDs);
m_GPUDrivenProcessor.DisableGPUDrivenRendering(unsupportedRendererGroupIDs);
}
Profiler.EndSample();
}
//@ Implement later...
private InstanceHandle AppendNewInstance(int rendererGroupID, in Matrix4x4 instanceTransform)
{
throw new NotImplementedException();
}
//@ Additionally we need to implement the way to tie external transforms (not Transform components) with instances.
//@ So that an individual instance could be transformed externally and then updated in the drawer.
private JobHandle ScheduleQueryRendererGroupInstancesJob(NativeArray<int> rendererGroupIDs, NativeArray<InstanceHandle> instances)
{
return m_BatchersContext.ScheduleQueryRendererGroupInstancesJob(rendererGroupIDs, instances);
}
private JobHandle ScheduleQueryRendererGroupInstancesJob(NativeArray<int> rendererGroupIDs, NativeList<InstanceHandle> instances)
{
return m_BatchersContext.ScheduleQueryRendererGroupInstancesJob(rendererGroupIDs, instances);
}
private JobHandle ScheduleQueryRendererGroupInstancesJob(NativeArray<int> rendererGroupIDs, NativeArray<int> instancesOffset, NativeArray<int> instancesCount, NativeList<InstanceHandle> instances)
{
return m_BatchersContext.ScheduleQueryRendererGroupInstancesJob(rendererGroupIDs, instancesOffset, instancesCount, instances);
}
private JobHandle ScheduleQueryMeshInstancesJob(NativeArray<int> sortedMeshIDs, NativeList<InstanceHandle> instances)
{
return m_BatchersContext.ScheduleQueryMeshInstancesJob(sortedMeshIDs, instances);
}
private void ClassifyMaterials(NativeArray<int> materials, out NativeList<int> unsupportedMaterials,
out NativeList<int> supportedMaterials, out NativeList<GPUDrivenPackedMaterialData> supportedPackedMaterialDatas, Allocator allocator)
{
supportedMaterials = new NativeList<int>(materials.Length, allocator);
unsupportedMaterials = new NativeList<int>(materials.Length, allocator);
supportedPackedMaterialDatas = new NativeList<GPUDrivenPackedMaterialData>(materials.Length, allocator);
if (materials.Length > 0)
{
new ClassifyMaterialsJob
{
materialIDs = materials.AsReadOnly(),
batchMaterialHash = m_Batcher.instanceCullingBatcher.batchMaterialHash.AsReadOnly(),
unsupportedMaterialIDs = unsupportedMaterials,
supportedMaterialIDs = supportedMaterials,
supportedPackedMaterialDatas = supportedPackedMaterialDatas
}.Run();
}
}
private NativeList<int> FindUnsupportedRenderers(NativeArray<int> unsupportedMaterials)
{
NativeList<int> unsupportedRenderers = new NativeList<int>(Allocator.TempJob);
if (unsupportedMaterials.Length > 0)
{
new FindUnsupportedRenderersJob
{
unsupportedMaterials = unsupportedMaterials.AsReadOnly(),
materialIDArrays = m_BatchersContext.sharedInstanceData.materialIDArrays,
rendererGroups = m_BatchersContext.sharedInstanceData.rendererGroupIDs,
unsupportedRenderers = unsupportedRenderers,
}.Run();
}
return unsupportedRenderers;
}
private NativeHashSet<int> GetMaterialsWithChangedPackedMaterial(NativeArray<int> materials, NativeArray<GPUDrivenPackedMaterialData> packedMaterialDatas, Allocator allocator)
{
NativeHashSet<int> filteredMaterials = new NativeHashSet<int>(materials.Length, allocator);
new GetMaterialsWithChangedPackedMaterialJob
{
materialIDs = materials.AsReadOnly(),
packedMaterialDatas = packedMaterialDatas.AsReadOnly(),
packedMaterialHash = batcher.instanceCullingBatcher.packedMaterialHash.AsReadOnly(),
filteredMaterials = filteredMaterials
}.Run();
return filteredMaterials;
}
private NativeList<int> FindRenderersFromMaterials(NativeArray<int> sortedExcludeRenderers, NativeHashSet<int> materials, Allocator rendererListAllocator)
{
var sharedInstanceData = m_BatchersContext.sharedInstanceData;
NativeList<int> renderers = new NativeList<int>(sharedInstanceData.rendererGroupIDs.Length, rendererListAllocator);
var jobHandle = new FindRenderersFromMaterialJob
{
materialIDs = materials.AsReadOnly(),
materialIDArrays = sharedInstanceData.materialIDArrays,
rendererGroupIDs = sharedInstanceData.rendererGroupIDs,
sortedExcludeRendererIDs = sortedExcludeRenderers.AsReadOnly(),
selectedRenderGroups = renderers.AsParallelWriter(),
}.ScheduleBatch(sharedInstanceData.rendererGroupIDs.Length, FindRenderersFromMaterialJob.k_BatchSize);
jobHandle.Complete();
return renderers;
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct ClassifyMaterialsJob : IJob
{
[ReadOnly] public NativeParallelHashMap<int, BatchMaterialID>.ReadOnly batchMaterialHash;
[ReadOnly] public NativeArray<int>.ReadOnly materialIDs;
public NativeList<int> supportedMaterialIDs;
public NativeList<int> unsupportedMaterialIDs;
public NativeList<GPUDrivenPackedMaterialData> supportedPackedMaterialDatas;
public void Execute()
{
var usedMaterialIDs = new NativeList<int>(4, Allocator.TempJob);
foreach (var materialID in materialIDs)
{
if (batchMaterialHash.ContainsKey(materialID))
usedMaterialIDs.Add(materialID);
}
if (usedMaterialIDs.IsEmpty)
{
usedMaterialIDs.Dispose();
return;
}
unsupportedMaterialIDs.Resize(usedMaterialIDs.Length, NativeArrayOptions.UninitializedMemory);
supportedMaterialIDs.Resize(usedMaterialIDs.Length, NativeArrayOptions.UninitializedMemory);
supportedPackedMaterialDatas.Resize(usedMaterialIDs.Length, NativeArrayOptions.UninitializedMemory);
int unsupportedMaterialCount = GPUDrivenProcessor.ClassifyMaterials(usedMaterialIDs.AsArray(), unsupportedMaterialIDs.AsArray(), supportedMaterialIDs.AsArray(), supportedPackedMaterialDatas.AsArray());
unsupportedMaterialIDs.Resize(unsupportedMaterialCount, NativeArrayOptions.ClearMemory);
supportedMaterialIDs.Resize(usedMaterialIDs.Length - unsupportedMaterialCount, NativeArrayOptions.ClearMemory);
supportedPackedMaterialDatas.Resize(supportedMaterialIDs.Length, NativeArrayOptions.ClearMemory);
usedMaterialIDs.Dispose();
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct FindUnsupportedRenderersJob : IJob
{
[ReadOnly] public NativeArray<int>.ReadOnly unsupportedMaterials;
[ReadOnly] public NativeArray<SmallIntegerArray>.ReadOnly materialIDArrays;
[ReadOnly] public NativeArray<int>.ReadOnly rendererGroups;
public NativeList<int> unsupportedRenderers;
public unsafe void Execute()
{
if (unsupportedMaterials.Length == 0)
return;
for (int arrayIndex = 0; arrayIndex < materialIDArrays.Length; arrayIndex++)
{
var materialIDs = materialIDArrays[arrayIndex];
int rendererID = rendererGroups[arrayIndex];
for (int i = 0; i < materialIDs.Length; i++)
{
int materialID = materialIDs[i];
if (unsupportedMaterials.Contains(materialID))
{
unsupportedRenderers.Add(rendererID);
break;
}
}
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private unsafe struct FindRenderersFromMaterialJob : IJobParallelForBatch
{
public const int k_BatchSize = 128;
[ReadOnly] public NativeHashSet<int>.ReadOnly materialIDs;
[ReadOnly] public NativeArray<SmallIntegerArray>.ReadOnly materialIDArrays;
[ReadOnly] public NativeArray<int>.ReadOnly rendererGroupIDs;
[ReadOnly] public NativeArray<int>.ReadOnly sortedExcludeRendererIDs;
[WriteOnly] public NativeList<int>.ParallelWriter selectedRenderGroups;
public void Execute(int startIndex, int count)
{
int* renderersToAddPtr = stackalloc int[k_BatchSize];
var renderersToAdd = new UnsafeList<int>(renderersToAddPtr, k_BatchSize);
renderersToAdd.Length = 0;
for (int index = 0; index < count; index++)
{
var rendererIndex = startIndex + index;
var rendererID = rendererGroupIDs[rendererIndex];
// We ignore this renderer if it is in the excluded list.
if (sortedExcludeRendererIDs.BinarySearch(rendererID) >= 0)
continue;
var rendererMaterials = materialIDArrays[rendererIndex];
for (int materialIndex = 0; materialIndex < rendererMaterials.Length; materialIndex++)
{
var materialID = rendererMaterials[materialIndex];
if (materialIDs.Contains(materialID))
{
renderersToAdd.AddNoResize(rendererID);
break;
}
}
}
selectedRenderGroups.AddRangeNoResize(renderersToAddPtr, renderersToAdd.Length);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct GetMaterialsWithChangedPackedMaterialJob : IJob
{
[ReadOnly] public NativeArray<int>.ReadOnly materialIDs;
[ReadOnly] public NativeArray<GPUDrivenPackedMaterialData>.ReadOnly packedMaterialDatas;