-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathscene_streaming.cpp
More file actions
2388 lines (1945 loc) · 104 KB
/
Copy pathscene_streaming.cpp
File metadata and controls
2388 lines (1945 loc) · 104 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
/*
* Copyright (c) 2024-2026, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: Copyright (c) 2024-2026, NVIDIA CORPORATION.
* SPDX-License-Identifier: Apache-2.0
*/
#include <volk.h>
#include <fmt/format.h>
#include "scene_streaming.hpp"
#define STREAMING_DEBUG_FORCE_REQUESTS 0
namespace lodclusters {
static_assert(sizeof(shaderio::ClasBuildInfo) == sizeof(VkClusterAccelerationStructureBuildTriangleClusterInfoNV));
template <class T>
struct OffsetOrPointer
{
union
{
uint64_t offset;
T* pointer;
};
};
bool SceneStreaming::init(Resources* resources, const Scene* scene, const StreamingConfig& config)
{
assert(!m_resources && "no init before deinit");
assert(resources && scene);
Resources& res = *resources;
m_resources = resources;
m_scene = scene;
m_config = config;
m_shaderData = {};
m_shaders = {};
m_pipelines = {};
m_requiresClas = false;
m_lastUpdateIndex = 0;
m_frameIndex = 1; // intentionally start at 1
m_operationsSize = 0;
m_persistentGeometrySize = 0;
m_blasSize = 0;
m_clasOperationsSize = 0;
m_clasLowDetailSize = 0;
m_clasSingleMaxSize = 0;
m_clasScratchNewClasSize = 0;
m_clasScratchNewBuildSize = 0;
m_clasScratchMoveSize = 0;
m_clasScratchTotalSize = 0;
m_stats = {};
// some adjustments are required to make the config compatible
// need at least all lo-res groups of all geometries
m_config.maxGroups = std::max(m_config.maxGroups, uint32_t(scene->getActiveGeometryCount()));
if(m_config.maxClusters == 0)
{
m_config.maxClusters = config.maxGroups * scene->m_config.clusterGroupSize;
}
m_config.maxClusters =
std::max(m_config.maxClusters, uint32_t(scene->getActiveGeometryCount()) * scene->m_config.clusterGroupSize);
m_stats.maxLoadCount = m_config.maxPerFrameLoadRequests;
m_stats.maxUnloadCount = m_config.maxPerFrameUnloadRequests;
m_stats.maxGroups = m_config.maxGroups;
m_stats.maxClusters = m_config.maxClusters;
m_stats.maxTransferBytes = m_config.maxTransferMegaBytes * 1024 * 1024;
// setup descriptor set container
{
nvvk::DescriptorBindings bindings;
bindings.addBinding(BINDINGS_FRAME_UBO, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT);
bindings.addBinding(BINDINGS_READBACK_SSBO, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT);
bindings.addBinding(BINDINGS_GEOMETRIES_SSBO, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT);
bindings.addBinding(BINDINGS_SCENEBUILDING_SSBO, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT);
bindings.addBinding(BINDINGS_SCENEBUILDING_UBO, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT);
bindings.addBinding(BINDINGS_STREAMING_SSBO, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT);
bindings.addBinding(BINDINGS_STREAMING_UBO, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT);
m_dsetPack.init(bindings, res.m_device);
nvvk::createPipelineLayout(res.m_device, &m_pipelineLayout, {m_dsetPack.getLayout()},
{{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t)}});
}
if(!initShadersAndPipelines())
{
m_dsetPack.deinit();
return false;
}
uint32_t groupCountAlignment = std::max(std::max(STREAM_AGEFILTER_GROUPS_WORKGROUP, STREAM_UPDATE_SCENE_WORKGROUP),
STREAM_COMPACTION_OLD_CLAS_WORKGROUP);
uint32_t clusterCountAlignment = STREAM_COMPACTION_NEW_CLAS_WORKGROUP;
// setup streaming management
m_requestsTaskQueue = {};
m_updatesTaskQueue = {};
m_storageTaskQueue = {};
m_requests.init(res, m_config, groupCountAlignment, clusterCountAlignment);
m_resident.init(res, m_config, groupCountAlignment, clusterCountAlignment);
m_updates.init(res, m_config, uint32_t(m_scene->getActiveGeometryCount()), groupCountAlignment, clusterCountAlignment);
m_storage.init(res, m_config);
// storage uses block allocator, max may be less than what we asked for
m_stats.maxDataBytes = m_storage.getMaxDataSize();
m_operationsSize += logMemoryUsage(m_requests.getOperationsSize(), "operations", "stream requests");
m_operationsSize += logMemoryUsage(m_resident.getOperationsSize(), "operations", "stream resident");
m_operationsSize += logMemoryUsage(m_updates.getOperationsSize(), "operations", "stream updates");
m_operationsSize += logMemoryUsage(m_storage.getOperationsSize(), "operations", "stream storage");
res.createBuffer(m_shaderBuffer, sizeof(shaderio::SceneStreaming),
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT
| VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
NVVK_DBG_NAME(m_shaderBuffer.buffer);
m_operationsSize += logMemoryUsage(m_shaderBuffer.bufferSize, "operations", "stream shaderio");
// seed lo res geometry
initGeometries(res, scene);
return true;
}
void SceneStreaming::updateBindings(const nvvk::Buffer& sceneBuildingBuffer)
{
nvvk::WriteSetContainer writeSets;
writeSets.append(m_dsetPack.makeWrite(BINDINGS_FRAME_UBO), m_resources->m_commonBuffers.frameConstants);
writeSets.append(m_dsetPack.makeWrite(BINDINGS_READBACK_SSBO), m_resources->m_commonBuffers.readBack);
writeSets.append(m_dsetPack.makeWrite(BINDINGS_GEOMETRIES_SSBO), m_shaderGeometriesBuffer);
writeSets.append(m_dsetPack.makeWrite(BINDINGS_SCENEBUILDING_SSBO), sceneBuildingBuffer);
writeSets.append(m_dsetPack.makeWrite(BINDINGS_SCENEBUILDING_UBO), sceneBuildingBuffer);
writeSets.append(m_dsetPack.makeWrite(BINDINGS_STREAMING_SSBO), m_shaderBuffer);
writeSets.append(m_dsetPack.makeWrite(BINDINGS_STREAMING_UBO), m_shaderBuffer);
vkUpdateDescriptorSets(m_resources->m_device, writeSets.size(), writeSets.data(), 0, nullptr);
}
void SceneStreaming::resetCachedBlas(Resources::BatchedUploader& uploader)
{
for(size_t geometryIndex = 0; geometryIndex < m_scene->getActiveGeometryCount(); geometryIndex++)
{
SceneStreaming::PersistentGeometry& persistentGeometry = m_persistentGeometries[geometryIndex];
persistentGeometry.cachedBlasUpdateFrame = 0;
persistentGeometry.cachedBlasLevel = TRAVERSAL_INVALID_LOD_LEVEL;
if(persistentGeometry.cachedBlasAllocation)
{
m_cachedBlasAllocator.subFree(persistentGeometry.cachedBlasAllocation);
}
}
// resets cachedBlasLevel and cachedBlasAddress
uploader.uploadBuffer(m_shaderGeometriesBuffer, m_shaderGeometries.data());
}
void SceneStreaming::resetCachedBlas()
{
if(m_requiresClas && m_config.allowBlasCaching)
{
Resources::BatchedUploader uploader(*m_resources);
resetCachedBlas(uploader);
uploader.flush();
}
}
void SceneStreaming::resetGeometryGroupAddresses(Resources::BatchedUploader& uploader)
{
// this function fills the geometry group addresses to be invalid
// except for the persistent lowest detail group
for(size_t geometryIndex = 0; geometryIndex < m_scene->getActiveGeometryCount(); geometryIndex++)
{
SceneStreaming::PersistentGeometry& persistentGeometry = m_persistentGeometries[geometryIndex];
shaderio::Geometry& shaderGeometry = m_shaderGeometries[geometryIndex];
const Scene::GeometryView& sceneGeometry = m_scene->getActiveGeometry(geometryIndex);
shaderio::LodLevel lastLodLevel = sceneGeometry.lodLevels.back();
uint64_t* groupAddresses = uploader.uploadBuffer(persistentGeometry.groupAddresses, (uint64_t*)nullptr);
for(uint32_t groupIndex = 0; groupIndex < lastLodLevel.groupOffset; groupIndex++)
{
groupAddresses[groupIndex] = STREAMING_INVALID_ADDRESS_START;
}
// except last group, which is always loaded
groupAddresses[lastLodLevel.groupOffset] = persistentGeometry.lowDetailGroupsData.address;
// also reset the number of groups loaded per lod-level, except last which is also always loaded.
uint32_t maxLodLevel = persistentGeometry.lodLevelsCount - 1;
for(uint32_t i = 0; i < maxLodLevel; i++)
{
persistentGeometry.lodLoadedGroupsCount[i] = 0;
}
persistentGeometry.lodLoadedGroupsCount[maxLodLevel] = 1;
}
}
void SceneStreaming::initGeometries(Resources& res, const Scene* scene)
{
// This function uploads all persistent per-geometry data.
// - hierarchy nodes for lod traversal
// - lowest detail geometry group & clusters
// - the address lookup array to find resident groups
// It also fills the geometry descriptor stored in
// m_shaderGeometries
Resources::BatchedUploader uploader(res);
m_shaderGeometries.resize(scene->getActiveGeometryCount());
m_persistentGeometries.resize(scene->getActiveGeometryCount());
uint32_t instancesOffset = 0;
for(size_t geometryIndex = 0; geometryIndex < scene->getActiveGeometryCount(); geometryIndex++)
{
shaderio::Geometry& shaderGeometry = m_shaderGeometries[geometryIndex];
SceneStreaming::PersistentGeometry& persistentGeometry = m_persistentGeometries[geometryIndex];
const Scene::GeometryView& sceneGeometry = m_scene->getActiveGeometry(geometryIndex);
size_t numGroups = sceneGeometry.groupInfos.size();
res.createBufferTyped(persistentGeometry.groupAddresses, numGroups, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
NVVK_DBG_NAME(persistentGeometry.groupAddresses.buffer);
size_t numNodes = sceneGeometry.lodNodes.size();
res.createBufferTyped(persistentGeometry.nodes, numNodes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
res.createBufferTyped(persistentGeometry.nodeBboxes, numNodes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
NVVK_DBG_NAME(persistentGeometry.nodes.buffer);
NVVK_DBG_NAME(persistentGeometry.nodeBboxes.buffer);
uint32_t numLodLevels = sceneGeometry.lodLevelsCount;
res.createBufferTyped(persistentGeometry.lodLevels, numLodLevels, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
NVVK_DBG_NAME(persistentGeometry.lodLevels.buffer);
m_persistentGeometrySize += persistentGeometry.groupAddresses.bufferSize;
m_persistentGeometrySize += persistentGeometry.nodes.bufferSize;
m_persistentGeometrySize += persistentGeometry.nodeBboxes.bufferSize;
// setup shaderio
shaderGeometry = {};
shaderGeometry.bbox = sceneGeometry.bbox;
shaderGeometry.nodes = persistentGeometry.nodes.address;
shaderGeometry.nodeBboxes = persistentGeometry.nodeBboxes.address;
shaderGeometry.streamingGroupAddresses = persistentGeometry.groupAddresses.address;
shaderGeometry.lodLevelsCount = numLodLevels;
shaderGeometry.lodLevels = persistentGeometry.lodLevels.address;
shaderGeometry.cachedBlasAddress = 0;
shaderGeometry.cachedBlasLodLevel = TRAVERSAL_INVALID_LOD_LEVEL;
shaderGeometry.instancesCount = sceneGeometry.instanceReferenceCount * scene->getGeometryInstanceFactor();
shaderGeometry.instancesOffset = instancesOffset;
instancesOffset += shaderGeometry.instancesCount;
persistentGeometry.lodLevelsCount = numLodLevels;
for(uint32_t i = 0; i < numLodLevels; i++)
{
persistentGeometry.lodGroupsCount[i] = sceneGeometry.lodLevels[i].groupCount;
}
// basic uploads
uploader.uploadBuffer(persistentGeometry.nodes, sceneGeometry.lodNodes.data());
uploader.uploadBuffer(persistentGeometry.nodeBboxes, sceneGeometry.lodNodeBboxes.data());
uploader.uploadBuffer(persistentGeometry.lodLevels, sceneGeometry.lodLevels.data());
// seed lowest detail group, which must have just a single cluster
shaderio::LodLevel lastLodLevel = sceneGeometry.lodLevels.back();
const Scene::GroupInfo groupInfo = sceneGeometry.groupInfos[lastLodLevel.groupOffset];
Scene::GroupView groupView(sceneGeometry.groupData, groupInfo);
assert(groupInfo.clusterCount == 1);
GeometryGroup geometryGroup = {uint32_t(geometryIndex), lastLodLevel.groupOffset};
uint32_t lastClustersCount = groupInfo.clusterCount;
uint64_t lastGroupSize = groupInfo.getDeviceSize();
res.createBuffer(persistentGeometry.lowDetailGroupsData, lastGroupSize, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
NVVK_DBG_NAME(persistentGeometry.lowDetailGroupsData.buffer);
m_persistentGeometrySize += persistentGeometry.lowDetailGroupsData.bufferSize;
assert(lastClustersCount <= 0xFFFFFFFF);
assert(m_resident.canAllocateGroup(uint32_t(lastClustersCount)));
StreamingResident::Group* rgroup = m_resident.addGroup(geometryGroup, lastClustersCount, groupInfo.triangleCount);
rgroup->deviceAddress = persistentGeometry.lowDetailGroupsData.address;
rgroup->lodLevel = groupInfo.lodLevel;
persistentGeometry.lodLoadedGroupsCount[groupInfo.lodLevel] = 1;
// setup and upload geometry data for the lowest detail group
void* loGroupData = uploader.uploadBuffer(persistentGeometry.lowDetailGroupsData, (void*)nullptr);
Scene::fillGroupRuntimeData(groupInfo, groupView, geometryGroup.groupID, rgroup->groupResidentID,
rgroup->clusterResidentID, loGroupData, persistentGeometry.lowDetailGroupsData.bufferSize);
const shaderio::BBox& lowDetailBBox = groupView.clusterBboxes[0];
const float lowDetailBBoxExtent = std::max(glm::length(lowDetailBBox.hi - lowDetailBBox.lo), 1e-6f);
shaderGeometry.lowDetailClusterID = rgroup->clusterResidentID;
shaderGeometry.lowDetailTriangles = groupInfo.triangleCount;
shaderGeometry.bbox.longestEdge = lowDetailBBox.longestEdge / lowDetailBBoxExtent;
}
// this will set all addresses to invalid, except lowest detail geometry group, which is persistently loaded.
resetGeometryGroupAddresses(uploader);
res.createBufferTyped(m_shaderGeometriesBuffer, scene->getActiveGeometryCount(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
NVVK_DBG_NAME(m_shaderGeometriesBuffer.buffer);
m_operationsSize += logMemoryUsage(m_shaderGeometriesBuffer.bufferSize, "operations", "stream geo buffer");
uploader.uploadBuffer(m_shaderGeometriesBuffer, m_shaderGeometries.data());
// initial residency table
m_resident.uploadInitialState(uploader, m_shaderData.resident);
uploader.flush();
}
void SceneStreaming::cmdBeginFrame(VkCommandBuffer cmd,
QueueState& cmdQueueState,
QueueState& asyncQueueState,
const FrameSettings& settings,
nvvk::ProfilerGpuTimer& profiler)
{
// This function sets up all relevant streaming tasks for the frame
// and configures the content of `m_shaderData` which is uploaded
// and all streaming related kernels will operate with.
//
// The data within `m_shaderData` is stateful and new operations may
// modify it permanently so that future frames keep the state from the
// last run operations.
//
// - handle completed updates: to give back memory unloads within that update
// - handle completed storage transfers: to trigger scene updates now that geometry data is available
// - handle completed request: to trigger new loads/unloads etc.
// as a request produces one new update & storage task, these tasks must be handled before
// - make a new request
// likewise a new request requires an empty slot, hence requests must be handled before
//
// This function is called by the renderer.
auto timerSection = profiler.cmdFrameSection(cmd, "Stream Begin");
VkDevice device = m_resources->m_device;
// For each task queue we must ensure that we have one new task index
// available to acquire for any potential new work in this frame.
// The ordering in which we drain them matters, as was described above.
const bool ensureAcquisition = true;
// pop all completed old updates to recycle as much memory as we can
while(m_updatesTaskQueue.canPop(device, ensureAcquisition))
{
// handleCompletedUpdate
//
// The update operation has been completed on the GPU time line, therefore
// it is safe to fully recycle the memory as it can no longer be reached.
uint32_t popUpdateIndex = m_updatesTaskQueue.pop();
const StreamingUpdates::TaskInfo& update = m_updates.getCompletedTask(popUpdateIndex);
for(uint32_t g = 0; g < update.unloadCount; g++)
{
m_storage.free(update.unloadHandles[g]);
}
m_updatesTaskQueue.releaseTaskIndex(popUpdateIndex);
}
// Our task system allows that new updates can be either
// handled immediately in the current frame, or decoupled
// in a later frame.
//
// Decoupled allows for asynchronous uploads that can
// span multiple frames, while immediate means
// we guarantee transfers completed prior triggering
// operations.
uint32_t pushUpdateIndex = INVALID_TASK_INDEX;
// pop one completed storage transfer
if(m_storageTaskQueue.canPop(device, ensureAcquisition))
{
// handleCompletedStorage
//
// The upload of new data was completed, recycle the task and transfer space for future use.
// If we run in decoupled mode, then push the dependent updates with this frame.
uint32_t dependentIndex = INVALID_TASK_INDEX;
uint32_t popStorageIndex = m_storageTaskQueue.popWithDependent(dependentIndex);
m_storageTaskQueue.releaseTaskIndex(popStorageIndex);
// check if we use a decoupled update
if(dependentIndex != INVALID_TASK_INDEX)
{
pushUpdateIndex = dependentIndex;
}
}
bool isImmediateUpdate = false;
// pop and process one completed request:
// We read the requested load/unload operations from a completed frame.
// Within the function we try to make new geometry groups residents,
// and unloaded ones non-resident.
// This triggers a storage transfer within the provided command buffer.
if(m_requestsTaskQueue.canPop(device, ensureAcquisition))
{
uint32_t popRequestIndex = m_requestsTaskQueue.pop();
#if 1
// variant where we pop to latest request
// otherwise we do process requests in strict order
while(m_requestsTaskQueue.canPop(device, false))
{
// ignore previous request
m_requestsTaskQueue.releaseTaskIndex(popRequestIndex);
// and use next instead
popRequestIndex = m_requestsTaskQueue.pop();
}
#endif
if(m_requiresClas && m_config.usePersistentClasAllocator)
{
// we might want to increase the CLAS allocator's memory based on usage.
const StreamingRequests::TaskInfo& growRequest = m_requests.getCompletedTask(popRequestIndex);
// A request recorded at or after the frame of the last grow does reflect
// the grown state in its readback, so the compensation delta is retired.
// Older in-flight requests still report the pre-grow state and need it.
if(growRequest.shaderData->frameIndexU32[0] >= m_clasGrowFrameIndex)
{
m_clasGrowMaxSizedLeftDelta = 0;
}
m_clasGrowMaxSizedLeftDelta += tryGrowClas(cmd, growRequest);
}
uint32_t dependentIndex = handleCompletedRequest(cmd, cmdQueueState, asyncQueueState, settings, popRequestIndex);
// check if immediate update to perform
if(dependentIndex != INVALID_TASK_INDEX)
{
// cannot have deferred and immediate update
assert(pushUpdateIndex == INVALID_TASK_INDEX);
pushUpdateIndex = dependentIndex;
isImmediateUpdate = true;
}
}
// test if there is an update to be done this frame
if(pushUpdateIndex != INVALID_TASK_INDEX)
{
// Given we know all data was uploaded, we can run the updates to the scene
// in this frame, which ultimately fulfills a past request on the device.
//
// Within this frame compute shaders and other operations, will handle the data
// provided via values and pointers that are written into.
// m_shaderData
//
// This will mean the current frame can use the new data.
// both resident and update operations are a synchronized pair, hence
// single index is sufficient.
m_resident.applyTask(m_shaderData.resident, pushUpdateIndex, m_frameIndex);
m_updates.applyTask(m_shaderData.update, pushUpdateIndex, m_frameIndex);
// we later want to detect the completion of the update task
// (this was the first thing we did in this function),
// so push it to task queue
m_updatesTaskQueue.push(pushUpdateIndex, cmdQueueState.getCurrentState());
m_lastUpdateIndex = pushUpdateIndex;
}
else
{
// no patch work this frame
m_shaderData.update.patchGroupsCount = 0;
m_shaderData.update.patchUnloadGroupsCount = 0;
m_shaderData.update.patchCachedBlasCount = 0;
m_shaderData.update.patchCachedClustersCount = 0;
m_shaderData.update.loadActiveGroupsOffset = 0;
m_shaderData.update.loadActiveClustersOffset = 0;
m_shaderData.update.newClasCount = 0;
m_shaderData.update.taskIndex = INVALID_TASK_INDEX;
m_shaderData.update.frameIndex = m_frameIndex;
}
// push new request
{
// every frame we will setup new space for new requests made by the device.
// This is the type of request that we reacted on a few lines above in the
// `handleCompletedRequest` function.
uint32_t pushRequestIndex = m_requestsTaskQueue.acquireTaskIndex();
// the acquisition must be guaranteed by design, as we always handle requests.
assert(pushRequestIndex != INVALID_TASK_INDEX);
// get space for request storage
// and setup this frame's m_shaderData, so that the streaming
// logic can write to the appropriate pointers.
m_requests.applyTask(m_shaderData.request, pushRequestIndex, m_frameIndex);
}
if(m_requiresClas && m_config.usePersistentClasAllocator)
{
// clears the size ranges to zero
m_clasAllocator.cmdBeginFrame(cmd);
}
m_shaderData.frameIndex = m_frameIndex;
m_shaderData.ageThreshold = settings.ageThreshold;
m_shaderData.useBlasCaching = settings.useBlasCaching ? 1 : 0;
m_shaderData.clasPositionTruncateBits = m_clasTriangleInput.minPositionTruncateBitCount;
// upload final configurations for this frame
vkCmdUpdateBuffer(cmd, m_shaderBuffer.buffer, 0, sizeof(m_shaderData), &m_shaderData);
}
uint32_t SceneStreaming::handleCompletedRequest(VkCommandBuffer cmd,
QueueState& cmdQueueState,
QueueState& asyncQueueState,
const FrameSettings& settings,
uint32_t popRequestIndex)
{
// This function handles the requests from the device to upload new geometry groups,
// or unload some that haven't been used in a while.
// The readback of the data is guaranteed to have completed at this point.
// Uploading will try to handle as much requests as we have memory for.
// Uploading can be done through an async transfer or on the provided command buffer.
// After an upload is completed an update task must be run, we can
// run this task immediately or deferred (see later).
//
// Only called in the `SceneStreaming::cmdBeginFrame` function.
const StreamingRequests::TaskInfo& request = m_requests.getCompletedTask(popRequestIndex);
// during recording of requests the counters may exceed the limits
// however the data is always ensured to be within.
uint32_t loadCount = std::min(request.shaderData->maxLoads, request.shaderData->loadCounter);
uint32_t unloadCount = std::min(request.shaderData->maxUnloads, request.shaderData->unloadCounter);
{
const char* errorCause = nullptr;
uint32_t errorValue = 0;
if(request.shaderData->errorUpdate != 0)
{
errorCause = "update";
errorValue = request.shaderData->errorUpdate;
}
else if(request.shaderData->errorAgeFilter != 0)
{
errorCause = "age filter";
errorValue = request.shaderData->errorAgeFilter;
}
else if(request.shaderData->errorClasNotFound != 0)
errorCause = "clas not found";
else if(request.shaderData->errorClasAlloc != 0)
errorCause = "clas alloc";
else if(request.shaderData->errorClasDealloc != 0)
errorCause = "clas dealloc";
else if(request.shaderData->errorClasList != 0)
errorCause = "clas list";
else if(request.shaderData->errorClasUsedVsAlloc != 0)
errorCause = "clas used vs. alloc";
if(errorCause)
{
LOGE("streaming: fatal error - %s (%u)\n", errorCause, errorValue);
assert(0 && "streaming fatal error");
exit(-1);
}
}
if(m_requiresClas)
{
if(m_config.usePersistentClasAllocator)
{
m_stats.usedClasBytes = request.shaderData->clasAllocatedUsedSize;
m_stats.wastedClasBytes = request.shaderData->clasAllocatedWastedSize;
m_stats.maxSizedLeft = request.shaderData->clasAllocatedMaxSizedLeft;
}
else
{
m_stats.usedClasBytes = request.shaderData->clasCompactionUsedSize;
m_stats.wastedClasBytes = 0;
m_stats.maxSizedLeft = uint32_t((m_resident.getAllocatedClasBytes() - request.shaderData->clasCompactionUsedSize)
/ (m_clasSingleMaxSize * m_scene->m_config.clusterGroupSize));
}
}
#if !STREAMING_DEBUG_FORCE_REQUESTS
if((!loadCount && !unloadCount) || !m_debugFrameLimit)
{
// no work to do
m_requestsTaskQueue.releaseTaskIndex(popRequestIndex);
return INVALID_TASK_INDEX;
}
#endif
// for debugging
if(m_debugFrameLimit > 0)
m_debugFrameLimit--;
uint32_t pushStorageIndex = m_storageTaskQueue.acquireTaskIndex();
uint32_t pushUpdateIndex = m_updatesTaskQueue.acquireTaskIndex();
// early out if we are not able to acquire both tasks to serve the request
if(pushStorageIndex == INVALID_TASK_INDEX || pushUpdateIndex == INVALID_TASK_INDEX)
{
// give back acquisitions we don't make use of
if(pushStorageIndex != INVALID_TASK_INDEX)
{
m_storageTaskQueue.releaseTaskIndex(pushStorageIndex);
}
if(pushUpdateIndex != INVALID_TASK_INDEX)
{
m_updatesTaskQueue.releaseTaskIndex(pushUpdateIndex);
}
m_requestsTaskQueue.releaseTaskIndex(popRequestIndex);
return INVALID_TASK_INDEX;
}
StreamingStorage::TaskInfo& storageTask = m_storage.getNewTask(pushStorageIndex);
StreamingUpdates::TaskInfo& updateTask = m_updates.getNewTask(pushUpdateIndex);
bool useBlasCaching = m_requiresClas && m_config.allowBlasCaching && settings.useBlasCaching;
// let's do unloads first, so we can recycle resident objects
for(uint32_t g = 0; g < unloadCount; g++)
{
GeometryGroup geometryGroup = request.unloadGeometryGroups[g];
assert(geometryGroup.geometryID < m_scene->getActiveGeometryCount());
assert(geometryGroup.groupID < m_scene->getActiveGeometry(geometryGroup.geometryID).totalClustersCount);
const StreamingResident::Group* group = m_resident.findGroup(geometryGroup);
if(!group)
{
// The group might already be removed through a previous request.
// This can happen cause it may take a while until the patch that really removes something
// is applied on GPU timeline.
continue;
}
// setup patch
uint32_t unloadIndex = updateTask.unloadCount++;
shaderio::StreamingPatch& patch = updateTask.unloadPatches[unloadIndex];
patch.geometryID = geometryGroup.geometryID;
patch.groupID = geometryGroup.groupID;
patch.groupAddress = STREAMING_INVALID_ADDRESS_START;
// note actual storage memory cannot be recycled here, cause only
// once the new "update" operation was completed, the gpu's scene graph
// will not use the data anymore.
// So defer the actual unloading to the `SceneStreaming::handleCompletedUpdate`
// above.
assert(group->storageHandle);
updateTask.unloadHandles[unloadIndex] = group->storageHandle;
assert(m_persistentGeometries[geometryGroup.geometryID].lodLoadedGroupsCount[group->lodLevel] > 0);
m_persistentGeometries[geometryGroup.geometryID].lodLoadedGroupsCount[group->lodLevel]--;
// and remove from active resident
m_resident.removeGroup(group->groupResidentID);
// append to geometry patch list if necessary
if(useBlasCaching && m_persistentGeometries[geometryGroup.geometryID].cachedBlasUpdateFrame != m_frameIndex)
{
m_persistentGeometries[geometryGroup.geometryID].cachedBlasUpdateFrame = m_frameIndex;
uint32_t geometryPatchIndex = updateTask.geometryCachedCount++;
shaderio::StreamingGeometryPatch& geometryPatch = updateTask.geometryPatches[geometryPatchIndex];
geometryPatch.geometryID = geometryGroup.geometryID;
}
}
// for ray tracing
// we have two different clas memory management systems and for both
// one needs to see how much space is left for future allocations
// - move clas to be compacted all the time
uint64_t clasMovedUsedSize = request.shaderData->clasCompactionUsedSize;
uint64_t clasMovedReservedSize = m_resident.getAllocatedClasBytes();
// - a persistent allocator implemented on the gpu.
// when the clas storage was grown after this request was recorded,
// we may actually have more available than its readback reports
uint32_t clasAllocatedMaxSizedLeft = request.shaderData->clasAllocatedMaxSizedLeft + m_clasGrowMaxSizedLeftDelta;
// Need to account for clas operations that happen on the gpu timeline after this request's
// frame. They indirectly reduce the budget we are guaranteed to have left for building new clas.
StreamingUpdates::NewInfo futureNew = m_updates.getFutureNew(request.shaderData->frameIndexU32[0]);
clasMovedUsedSize += m_clasSingleMaxSize * futureNew.clusters;
clasAllocatedMaxSizedLeft -= std::min(clasAllocatedMaxSizedLeft, futureNew.groups);
uint32_t clasBuildOffset = 0;
uint64_t clasBuildSize = 0;
// all newly added groups will be appended to the active list
updateTask.loadActiveGroupsOffset = m_resident.getLoadActiveGroupsOffset();
updateTask.loadActiveClustersOffset = m_resident.getLoadActiveClustersOffset();
uint64_t transferBytes = 0;
m_stats.couldNotAllocateClas = 0;
m_stats.couldNotTransfer = 0;
m_stats.couldNotAllocateGroup = 0;
m_stats.couldNotStore = 0;
m_stats.uncompletedLoadCount = 0;
for(uint32_t g = 0; g < loadCount; g++)
{
GeometryGroup geometryGroup = request.loadGeometryGroups[g];
assert(geometryGroup.geometryID < m_scene->getActiveGeometryCount());
assert(geometryGroup.groupID < m_scene->getActiveGeometry(geometryGroup.geometryID).totalClustersCount);
if(m_resident.findGroup(geometryGroup))
{
// It could take more than one frame until the patch that handles the load
// is activated on the GPU timeline, and until then the same requests might be
// made.
continue;
}
const Scene::GeometryView& sceneGeometry = m_scene->getActiveGeometry(geometryGroup.geometryID);
// figure out size of this geometry group.
// This includes all relevant cluster data, including vertices, triangle indices...
const Scene::GroupInfo groupInfo = sceneGeometry.groupInfos[geometryGroup.groupID];
uint32_t clusterCount = groupInfo.clusterCount;
uint64_t groupDeviceSize = groupInfo.getDeviceSize();
uint64_t groupClasSize = 0;
bool canAllocateClas = true;
if(m_requiresClas)
{
groupClasSize = m_clasSingleMaxSize * clusterCount;
// must always fit in scratch
assert((clasBuildSize + groupClasSize) <= m_clasScratchNewClasSize);
if(m_config.usePersistentClasAllocator)
{
canAllocateClas = clasAllocatedMaxSizedLeft > 0;
}
else
{
canAllocateClas = (clasMovedUsedSize + (clasBuildSize + groupClasSize)) <= clasMovedReservedSize;
}
}
uint64_t deviceAddress;
nvvk::BufferSubAllocation storageHandle;
bool canTransfer = m_storage.canTransfer(storageTask, groupDeviceSize);
bool canStore = m_storage.allocate(storageHandle, geometryGroup, groupDeviceSize, deviceAddress);
bool canAllocateGroup = m_resident.canAllocateGroup(clusterCount);
// test if we can allocate
if(!canTransfer || !canStore || !canAllocateGroup || !canAllocateClas)
{
m_stats.couldNotAllocateClas += (!canAllocateClas);
m_stats.couldNotTransfer += (!canTransfer);
m_stats.couldNotAllocateGroup += (!canAllocateGroup);
m_stats.couldNotStore += (!canStore);
if(canStore)
{
// return memory on failure
m_storage.free(storageHandle);
}
if(clusterCount < 8)
{
m_stats.uncompletedLoadCount += loadCount - g;
break; // heuristic if small groups don't fit anymore then we fully break
}
else
{
m_stats.uncompletedLoadCount++;
continue;
}
}
StreamingResident::Group* residentGroup = m_resident.addGroup(geometryGroup, clusterCount, groupInfo.triangleCount);
residentGroup->storageHandle = storageHandle;
residentGroup->deviceAddress = deviceAddress;
residentGroup->lodLevel = groupInfo.lodLevel;
void* groupData = m_storage.appendTransfer(storageTask, residentGroup->storageHandle);
assert(deviceAddress % 16 == 0);
{
Scene::GroupView groupView(sceneGeometry.groupData, groupInfo);
if(groupInfo.uncompressedSizeBytes)
{
Scene::decompressGroup(groupInfo, groupView, groupData, groupDeviceSize);
}
else
{
// simply copy data as is, the streaming patch will take care of modifying the data
// where needed
memcpy(groupData, groupView.raw, groupView.rawSize);
}
}
m_persistentGeometries[geometryGroup.geometryID].lodLoadedGroupsCount[groupInfo.lodLevel]++;
// append to geometry patch list if necessary
if(useBlasCaching && m_persistentGeometries[geometryGroup.geometryID].cachedBlasUpdateFrame != m_frameIndex)
{
m_persistentGeometries[geometryGroup.geometryID].cachedBlasUpdateFrame = m_frameIndex;
uint32_t geometryPatchIndex = updateTask.geometryCachedCount++;
shaderio::StreamingGeometryPatch& geometryPatch = updateTask.geometryPatches[geometryPatchIndex];
geometryPatch.geometryID = geometryGroup.geometryID;
}
// setup patch
shaderio::StreamingPatch& patch = updateTask.loadPatches[updateTask.loadCount++];
patch.geometryID = geometryGroup.geometryID;
patch.groupID = geometryGroup.groupID;
patch.groupAddress = deviceAddress;
patch.groupResidentID = residentGroup->groupResidentID;
patch.clusterResidentID = residentGroup->clusterResidentID;
patch.clasBuildOffset = clasBuildOffset;
patch.clusterCount = groupInfo.clusterCount;
patch.lodLevel = groupInfo.lodLevel;
clasBuildOffset += clusterCount;
clasBuildSize += groupClasSize;
clasAllocatedMaxSizedLeft--;
// stats
transferBytes += groupInfo.sizeBytes;
}
// now that all loads are done, the removed groups' resident IDs can be
// recycled for future tasks
m_resident.flushRemovedGroups();
updateTask.newClusterCount = clasBuildOffset;
#if !STREAMING_DEBUG_FORCE_REQUESTS
if(updateTask.loadCount == 0 && updateTask.unloadCount == 0)
{
// we ended up doing no work
m_requestsTaskQueue.releaseTaskIndex(popRequestIndex);
m_updatesTaskQueue.releaseTaskIndex(pushUpdateIndex);
m_storageTaskQueue.releaseTaskIndex(pushStorageIndex);
return INVALID_TASK_INDEX;
}
#endif
if(m_config.useAsyncTransfer)
{
// don't use immediate command buffer from main queue,
// but use transfer queue instead.
NVVK_CHECK(m_storage.m_taskCommandPool.acquireCommandBuffer(pushStorageIndex, cmd));
VkCommandBufferBeginInfo cmdInfo = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
};
vkBeginCommandBuffer(cmd, &cmdInfo);
}
// evaluate geometry lod state and see if we need to
// rebuild the cached blas
if(useBlasCaching)
{
handleBlasCaching(updateTask, settings);
}
uint32_t transferCount = 0;
// finalize data for completed new residency & patch
// residency & updates always operate in synchronized pairs
transferBytes += m_updates.cmdUploadTask(cmd, pushUpdateIndex);
transferBytes += m_resident.cmdUploadTask(cmd, pushUpdateIndex);
transferCount += m_storage.cmdUploadTask(cmd);
transferCount += 2;
if(updateTask.loadCount)
{
// only log to stats for loads
m_stats.transferBytes = transferBytes;
m_stats.transferCount = transferCount;
m_stats.loadCount = updateTask.loadCount;
}
if(updateTask.unloadCount)
{
m_stats.unloadCount = updateTask.unloadCount;
}
// When we use async we can either wait until async completed (can take more than a frame)
// or we guarantee it completes for the frame we are currently preparing within `cmd`.
// When not using async we always know the transfer completes within the current frame.
bool useDecoupledUpdate = m_config.useAsyncTransfer && m_config.useDecoupledAsyncTransfer;
nvvk::SemaphoreState storageSemaphoreState =
m_config.useAsyncTransfer ? asyncQueueState.getCurrentState() : cmdQueueState.getCurrentState();
if(m_config.useAsyncTransfer)
{
vkEndCommandBuffer(cmd);
if(!m_config.useDecoupledAsyncTransfer)
{
// if not using decoupled, then let immediate command buffer's queue wait for this
// transfer to be completed
// get wait from async queue
VkSemaphoreSubmitInfo semWaitInfo = asyncQueueState.getWaitSubmit(VK_PIPELINE_STAGE_2_TRANSFER_BIT);
// push it for use in primary queue
cmdQueueState.m_pendingWaits.push_back(semWaitInfo);
}
// trigger async transfer queue submit
VkSemaphoreSubmitInfo semSubmitInfo = asyncQueueState.advanceSignalSubmit(VK_PIPELINE_STAGE_2_TRANSFER_BIT);
VkCommandBufferSubmitInfo cmdBufInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO};
cmdBufInfo.commandBuffer = cmd;
VkSubmitInfo2 submits = {VK_STRUCTURE_TYPE_SUBMIT_INFO_2_KHR};
submits.pCommandBufferInfos = &cmdBufInfo;
submits.commandBufferInfoCount = 1;
submits.pSignalSemaphoreInfos = &semSubmitInfo;
submits.signalSemaphoreInfoCount = 1;
vkQueueSubmit2(asyncQueueState.m_queue, 1, &submits, nullptr);
}
// give back the index for future write operations
m_requestsTaskQueue.releaseTaskIndex(popRequestIndex);
// enqueue the storage task
// the dependentIndex may be set to the pushUpdateIndex if we use decoupled
m_storageTaskQueue.push(pushStorageIndex, storageSemaphoreState, useDecoupledUpdate ? pushUpdateIndex : INVALID_TASK_INDEX);
// otherwise, we return update task to be handled directly in this frame
return useDecoupledUpdate ? INVALID_TASK_INDEX : pushUpdateIndex;
}
void SceneStreaming::handleBlasCaching(StreamingUpdates::TaskInfo& updateTask, const FrameSettings& settings)
{
uint32_t writeIndex = 0;
uint32_t cachedBuildsTotal = 0;
uint32_t cachedClustersTotal = 0;
#if STREAMING_DEBUG_FORCE_REQUESTS
if(updateTask.geometryCachedCount == 0)
{
updateTask.geometryPatches[updateTask.geometryCachedCount++].geometryID = 0;
}
#endif
for(uint32_t g = 0; g < updateTask.geometryCachedCount; g++)
{
shaderio::StreamingGeometryPatch sgpatch = updateTask.geometryPatches[g];
PersistentGeometry& persistentGeometry = m_persistentGeometries[sgpatch.geometryID];
const Scene::GeometryView& geometryView = m_scene->getActiveGeometry(sgpatch.geometryID);
uint32_t cachedClustersCount = 0;
uint32_t blasCacheMinLevel =
persistentGeometry.lodLevelsCount - std::min(settings.blasCacheMinLevel, persistentGeometry.lodLevelsCount);
// skip last level, always exists as low detail blas
for(uint32_t i = blasCacheMinLevel; i < persistentGeometry.lodLevelsCount - 1; i++)
{
// fully loaded
if(persistentGeometry.lodGroupsCount[i] == persistentGeometry.lodLoadedGroupsCount[i])
{
uint32_t groupCount = geometryView.lodLevels[i].groupCount;
uint32_t groupOffset = geometryView.lodLevels[i].groupOffset;
uint32_t cachedClustersCount = geometryView.lodLevels[i].clusterCount;
// check if it fits
if(cachedClustersCount <= STREAMING_CACHED_BLAS_MAX_CLUSTERS)
{
sgpatch.cachedBlasLodLevel = i;
break;
}
else
{