This repository was archived by the owner on Sep 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathEncodeHwBvh3_1.hlsl
More file actions
2024 lines (1693 loc) · 80.5 KB
/
EncodeHwBvh3_1.hlsl
File metadata and controls
2024 lines (1693 loc) · 80.5 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) 2023-2025 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
#ifndef _ENCODE_HW_BVH_3_1_HLSL
#define _ENCODE_HW_BVH_3_1_HLSL
#if NO_SHADER_ENTRYPOINT == 0
//=====================================================================================================================
#include "../shadersClean/common/ShaderDefs.hlsli"
#define GC_DSTBUFFER
#define GC_DSTMETADATA
#define GC_SCRATCHBUFFER
#include "../shadersClean/build/BuildRootSignature.hlsli"
#define TASK_COUNTER_BUFFER ScratchGlobal
#define TASK_COUNTER_OFFSET (ShaderConstants.offsets.taskLoopCounters + TASK_LOOP_QBVH_COUNTER_OFFSET)
#define NUM_TASKS_DONE_OFFSET (ShaderConstants.offsets.taskLoopCounters + TASK_LOOP_QBVH_TASKS_DONE_OFFSET)
#include "TaskMacros.hlsl"
template<typename T>
T LoadInstanceDescBuffer(uint offset)
{
return InstanceDescBuffer.Load<T>(offset);
}
#include "IndirectArgBufferUtils.hlsl"
#define MAX_ELEMENTS_PER_THREAD 8
#define MAX_LDS_ELEMENTS_PER_THREADGROUP (MAX_ELEMENTS_PER_THREAD * BUILD_THREADGROUP_SIZE)
groupshared uint SharedMem[MAX_LDS_ELEMENTS_PER_THREADGROUP];
uint GetSharedMem(uint index)
{
return SharedMem[index];
}
void SetSharedMem(uint index, uint value)
{
SharedMem[index] = value;
}
#include "BuildCommonScratch.hlsl"
#endif
#if GPURT_BUILD_RTIP3_1
#include "rtip3_1.hlsli"
#include "EncodeHwBvhCommon.hlsl"
#include "QBVH8Common.hlsl"
#include "../shadersClean/common/LaneGroup.hlsli"
#include "PrimitiveStructureEncoder3_1.hlsl"
#include "OrientedBoundingBoxes.hlsl"
namespace Gfx12
{
//=====================================================================================================================
// Returns true to enable a separate leaf compression pass over all children of one internal node.
bool EnableLeafCompressionPass()
{
return (Settings.topLevelBuild == false) &&
(Settings.geometryType == GEOMETRY_TYPE_TRIANGLES) &&
((Settings.primCompressionFlags & PrimCompFlags::MultiPrim) ||
(Settings.maxPrimRangeSize > 2));
}
//=====================================================================================================================
// Returns true to enable the optimized wave parallel compression pass (only supports wave32 and maxPrimRangeSize<=4)
bool EnableWaveLeafCompressionPass()
{
#if BUILD_PARALLEL
return false;
#else
return EnableLeafCompressionPass();
#endif
}
//=====================================================================================================================
// Returns true to enable the legacy leaf compression pass (supports wave64 and larger prim range sizes)
bool EnableLegacyLeafCompressionPass()
{
#if BUILD_PARALLEL
return EnableLeafCompressionPass();
#else
return false;
#endif
}
//=====================================================================================================================
// Pack destination node index (128-byte chunk index) and child index in parent (maximum value of 7) into a single
// DWORD in global stack
uint PackStackDstNodeIdx(
uint dstNodeIdx,
uint indexInParent)
{
return (dstNodeIdx << 3) | indexInParent;
}
//=====================================================================================================================
uint GetStackDstIdx(
uint packedEntry)
{
return (packedEntry >> 3);
}
//=====================================================================================================================
uint GetStackDstIdxInParent(
uint packedEntry)
{
return (packedEntry & bits(3));
}
//=====================================================================================================================
static uint GetNodeArrayBaseInLds(
in uint localId, in uint maxNumChildren)
{
return (localId * maxNumChildren);
}
//=====================================================================================================================
// Insert candidaate child in node array
static void InsertChildInNodeArray(
in uint baseLdsOffset,
in uint baseScratchNodesOffset,
in uint numPrimRefs,
in uint childScratchNodeIdx,
inout_param(uint) nextLeafIdx,
inout_param(uint) nextBoxIdx)
{
uint childSlotIdx = 0;
if (IsLeafOrIsCollapsed(childScratchNodeIdx, baseScratchNodesOffset, numPrimRefs))
{
childSlotIdx = --nextLeafIdx;
}
else
{
childSlotIdx = nextBoxIdx++;
}
SharedMem[baseLdsOffset + childSlotIdx] = childScratchNodeIdx;
}
//=====================================================================================================================
// Build child node array from BVH2 treelet root by using surface area heuristics
static void BuildChildNodeArray(
in uint localId,
in uint baseScratchNodesOffset,
in uint numPrimRefs,
in uint subtreeRootScratchNodeIdx,
in uint maxNumChildren,
out_param(uint) numBoxChildren,
out_param(uint) numLeafChildren)
{
const uint baseLdsOffset = GetNodeArrayBaseInLds(localId, maxNumChildren);
const ScratchNode subtreeRootScratchNode = FetchScratchNode(baseScratchNodesOffset, subtreeRootScratchNodeIdx);
uint nextBoxIdx = 0;
uint nextLeafIdx = maxNumChildren;
if (IsLeafOrIsCollapsed(subtreeRootScratchNodeIdx, baseScratchNodesOffset, numPrimRefs))
{
InsertChildInNodeArray(baseLdsOffset,
baseScratchNodesOffset,
numPrimRefs,
subtreeRootScratchNodeIdx,
nextLeafIdx,
nextBoxIdx);
}
else
{
// Insert left child into node array
InsertChildInNodeArray(baseLdsOffset,
baseScratchNodesOffset,
numPrimRefs,
subtreeRootScratchNode.left_or_primIndex_or_instIndex,
nextLeafIdx,
nextBoxIdx);
// Insert right child into node array
InsertChildInNodeArray(baseLdsOffset,
baseScratchNodesOffset,
numPrimRefs,
subtreeRootScratchNode.right_or_geometryIndex,
nextLeafIdx,
nextBoxIdx);
}
// The following loop places box nodes at the front of the node array while all leaf children are placed
// starting from the back of the node array with empty nodes in the middle. The two arrays are tracked
// via two pointers, nextBoxIdx and nextLeafIdx
//
// [Box, Box, ..................., Leaf, Leaf]
// ^ ^
// nextBoxIdx nextLeafIdx
//
uint validChildCount = nextBoxIdx + (maxNumChildren - nextLeafIdx);
// Cached candidate node data (left and right child indices)
uint2 cachedCandidateData = uint2(0, 0);
while (validChildCount < maxNumChildren)
{
float surfaceAreaMax = 0.0;
uint candidateSlotIdx = INVALID_IDX;
// Pick the largest surface area node from current node array of internal nodes.
for (uint j = 0; j < nextBoxIdx; j++)
{
const uint candidateNodeIdx = SharedMem[baseLdsOffset + j];
const ScratchNode candidateNode = FetchScratchNode(baseScratchNodesOffset, candidateNodeIdx);
const float surfaceArea = candidateNode.sah_or_v2_or_instBasePtr.y;
// Pick the node with larger surface area. If the nodes have identical surface area, pick the
// last node for opening.
if (surfaceArea >= surfaceAreaMax)
{
surfaceAreaMax = surfaceArea;
candidateSlotIdx = j;
cachedCandidateData.x = candidateNode.left_or_primIndex_or_instIndex;
cachedCandidateData.y = candidateNode.right_or_geometryIndex;
}
}
// If there are no valid nodes to open, exit loop
if (candidateSlotIdx == INVALID_IDX)
{
break;
}
// Swap in the last box node in candidate slot and free last slot for opening. Below, C represents
// candidate box node with the largest surface area.
//
// [B, C, B..................., L, L]
// ^ ^
// nextBoxIdx nextLeafIdx
//
// Last box node in node array gets swapped with candidate node and the box node pointer moves back
// to allow insertion at the end of the list
//
// [B, B, C..................., L, L]
// ^ ^
// nextBoxIdx nextLeafIdx
//
nextBoxIdx--;
SharedMem[baseLdsOffset + candidateSlotIdx] = SharedMem[baseLdsOffset + nextBoxIdx];
InsertChildInNodeArray(
baseLdsOffset, baseScratchNodesOffset, numPrimRefs,
cachedCandidateData.x, nextLeafIdx, nextBoxIdx);
InsertChildInNodeArray(
baseLdsOffset, baseScratchNodesOffset, numPrimRefs,
cachedCandidateData.y, nextLeafIdx, nextBoxIdx);
// Update valid child count
validChildCount = nextBoxIdx + (maxNumChildren - nextLeafIdx);
}
// Assign box and leaf node count in node array to output variables
numBoxChildren = nextBoxIdx;
numLeafChildren = maxNumChildren - nextLeafIdx;
// Shift leaf nodes left to cover up empty spaces if any in the child node array
if (nextBoxIdx != nextLeafIdx)
{
for (uint i = 0; i < numLeafChildren; ++i)
{
SharedMem[baseLdsOffset + nextBoxIdx + i] = SharedMem[baseLdsOffset + nextLeafIdx + i];
}
}
}
//=====================================================================================================================
void WriteInstanceNode(
in AccelStructOffsets offsets,
in uint numPrimRefs,
in ScratchNode scratchNode,
in uint scratchNodeIndex,
in uint nodeOffset,
in uint parentNodePointer)
{
const uint instanceIndex = scratchNode.left_or_primIndex_or_instIndex;
const uint nodePointer = PackNodePointer(NODE_TYPE_USER_NODE_INSTANCE, nodeOffset);
InstanceDesc instanceDesc = LoadInstanceDesc(instanceIndex, LoadNumPrimAndOffset().primitiveOffset);
const uint blasRootNodePointer = scratchNode.splitBox_or_nodePointer;
const uint blasMetadataSize = scratchNode.numPrimitivesAndDoCollapse;
const uint geometryType = ExtractScratchNodeGeometryType(scratchNode.packedFlags);
CullIllegalInstances(blasMetadataSize, scratchNode, instanceDesc);
WriteInstanceNode3_1(instanceDesc,
geometryType,
instanceIndex,
nodePointer,
blasRootNodePointer,
blasMetadataSize,
offsets,
parentNodePointer);
// When rebraiding is disabled the destination index is just the instance index.
const uint destIndex = (Settings.enableRebraid) ? (scratchNodeIndex - numPrimRefs + 1) : instanceIndex;
DstBuffer.Store(offsets.primNodePtrs + (destIndex * sizeof(uint)), nodePointer);
}
//=====================================================================================================================
static void WriteLeafNode(
in uint scratchNodesScratchOffset,
in AccelStructOffsets offsets,
in uint numPrimRefs,
in ScratchNode scratchNode,
in uint scratchNodeIdx,
in uint primStructIdx,
in uint nodeOffset,
in uint parentNodePointer)
{
if (Settings.topLevelBuild)
{
Gfx12::WriteInstanceNode(offsets,
numPrimRefs,
scratchNode,
scratchNodeIdx,
nodeOffset,
parentNodePointer);
}
else
{
bool isTri1Valid = false;
bool isTri0Opaque = false;
bool isTri1Opaque = false;
uint primId0 = 0;
uint primId1 = 0;
uint geomId0 = 0;
uint geomId1 = 0;
TriangleData tri0 = (TriangleData) 0;
TriangleData tri1 = (TriangleData) 0;
const bool isQuadPrim =
Settings.enableEarlyPairCompression && IsScratchNodeQuadPrimitive(scratchNode);
if (isQuadPrim)
{
isTri1Valid = true;
isTri0Opaque = IsOpaqueNode(scratchNode.packedFlags);
isTri1Opaque = isTri0Opaque;
primId0 = GetScratchNodePrimitiveIndex(scratchNode, 0);
primId1 = GetScratchNodePrimitiveIndex(scratchNode, 1);
geomId0 = ExtractScratchNodeGeometryIndex(scratchNode);
geomId1 = geomId0;
tri0 = GetScratchNodeQuadVertices(scratchNodesScratchOffset, scratchNodeIdx, 0);
tri1 = GetScratchNodeQuadVertices(scratchNodesScratchOffset, scratchNodeIdx, 1);
}
else if (IsLeafNode(scratchNodeIdx, numPrimRefs) == false)
{
uint firstNodeIndex;
ScratchNode scratchNodeTri0;
uint secondNodeIndex;
ScratchNode scratchNodeTri1;
if (UsePrimIndicesArray())
{
firstNodeIndex = GetPrimRefIdx(FetchSortedPrimIndex(ShaderConstants.offsets.primIndicesSorted,
scratchNode.sortedPrimIndex),
numPrimRefs);
scratchNodeTri0 = FetchScratchNode(scratchNodesScratchOffset, firstNodeIndex);
secondNodeIndex = GetPrimRefIdx(FetchSortedPrimIndex(ShaderConstants.offsets.primIndicesSorted,
scratchNode.sortedPrimIndex + 1),
numPrimRefs);
scratchNodeTri1 = FetchScratchNode(scratchNodesScratchOffset, secondNodeIndex);
}
else if (CollapseAnyPairs())
{
firstNodeIndex = scratchNode.left_or_primIndex_or_instIndex;
scratchNodeTri0 = FetchScratchNode(scratchNodesScratchOffset, firstNodeIndex);
secondNodeIndex = scratchNode.right_or_geometryIndex;
scratchNodeTri1 = FetchScratchNode(scratchNodesScratchOffset, secondNodeIndex);
}
else
{
firstNodeIndex = scratchNode.left_or_primIndex_or_instIndex;
scratchNodeTri0 = FetchScratchNode(scratchNodesScratchOffset, firstNodeIndex);
secondNodeIndex = scratchNodeTri0.parent;
scratchNodeTri1 = FetchScratchNode(scratchNodesScratchOffset, secondNodeIndex);
}
isTri1Valid = true;
isTri0Opaque = IsOpaqueNode(scratchNodeTri0.packedFlags);
isTri1Opaque = IsOpaqueNode(scratchNodeTri1.packedFlags);
primId0 = scratchNodeTri0.left_or_primIndex_or_instIndex;
primId1 = scratchNodeTri1.left_or_primIndex_or_instIndex;
geomId0 = ExtractScratchNodeGeometryIndex(scratchNodeTri0);
geomId1 = ExtractScratchNodeGeometryIndex(scratchNodeTri1);
tri0.v0 = scratchNodeTri0.bbox_min_or_v0;
tri0.v1 = scratchNodeTri0.bbox_max_or_v1;
tri0.v2 = scratchNodeTri0.sah_or_v2_or_instBasePtr;
tri1.v0 = scratchNodeTri1.bbox_min_or_v0;
tri1.v1 = scratchNodeTri1.bbox_max_or_v1;
tri1.v2 = scratchNodeTri1.sah_or_v2_or_instBasePtr;
}
else
{
isTri0Opaque = IsOpaqueNode(scratchNode.packedFlags);
primId0 = scratchNode.left_or_primIndex_or_instIndex;
geomId0 = ExtractScratchNodeGeometryIndex(scratchNode);
tri0.v0 = scratchNode.bbox_min_or_v0;
tri0.v1 = scratchNode.bbox_max_or_v1;
tri0.v2 = scratchNode.sah_or_v2_or_instBasePtr;
}
PrimStruct3_1::WritePairPrimStruct(tri0,
isTri0Opaque,
primId0,
geomId0,
isTri1Valid,
tri1,
isTri1Opaque,
primId1,
geomId1,
nodeOffset);
DstBuffer.Store(offsets.primNodePtrs + (primStructIdx * sizeof(uint)), nodeOffset);
}
}
//=====================================================================================================================
static void CompressLeafChildren(
uint scratchNodesScratchOffset,
AccelStructOffsets offsets,
uint parentBoxOffset,
uint primStructOffset,
uint numLeafChildren,
uint numBoxChildren,
uint numPrimRefs,
uint ldsOffset,
bool doRebraid)
{
// Filter node support assumes rebraid root children are not compressed
const bool isRebraidRootNode = doRebraid;
const bool compressMultiple =
(Settings.primCompressionFlags & PrimCompFlags::MultiPrim) && (isRebraidRootNode == false);
const bool enableTrailingZeroCompression = Settings.primCompressionFlags & PrimCompFlags::EnableTrailingZeroAndPrefix;
// TODO: Allow more pairs. Update can only handle one:
// - Parent pointer logic cannot handle multiple prims per slot in various places
// - Vertex data update does not yet support multiple prims
// - ExtractNodePointerOffset doesn't work with 4 bit node types
const uint maxPairs = compressMultiple ? 8 : 1;
TrianglePairDesc pairDescs[9];
float3 verts[16];
uint3 prefixSource = uint3(0, 0, 0);
uint3 planeDiffs = uint3(0, 0, 0);
uint planeUnion = 0;
uint primIdAnchor = 0;
uint primIdDiff = 0;
uint geoIdAnchor = 0;
uint geoIdDiff = 0;
uint uniqueVertexCount = 0;
uint triPairDescCount = 0;
PrimitiveStructure primStruct;
uint geometryInfoOffset = 0;
uint pairCount = 0;
const uint parentBoxPtr = PackNodePointer(NODE_TYPE_BOX_QUANTIZED_BVH8, parentBoxOffset);
QBVH8::WriteLeafNodeBaseOffset(parentBoxOffset, primStructOffset);
uint3 planeDiffsBackup;
uint uniqueVertexCountBackup;
uint primIdDiffBackup;
uint geoIdDiffBackup;
uint triPairDescCountBackup;
uint planeUnionBackup;
uint nodeIndex = INVALID_IDX;
uint leafChildIdx = 0;
uint rangeNextNode = INVALID_IDX;
uint firstNodeInPair = INVALID_IDX;
bool isTri1 = false;
uint rangePacketCount = 0;
uint rangeStartPair = 0;
uint lastValidChildInfoOffset = 0;
bool firstPairInRange = true;
const bool usePrimListArray = UsePrimIndicesArray();
uint currentIndexInArray;
uint numPrimsInArray;
uint primArrayStartIndex;
uint primIndexFirstInPair;
while ((leafChildIdx < numLeafChildren) || (rangeNextNode != INVALID_IDX))
{
if (rangeNextNode != INVALID_IDX)
{
nodeIndex = rangeNextNode;
}
else
{
nodeIndex = SharedMem[ldsOffset + leafChildIdx];
currentIndexInArray = 0;
numPrimsInArray = 1;
// Check for collapsed primitive range
if (IsLeafNode(nodeIndex, numPrimRefs) == false)
{
const ScratchNode scratchNode = FetchScratchNode(scratchNodesScratchOffset, nodeIndex);
GPU_ASSERT(scratchNode.numPrimitivesAndDoCollapse & 1);
if (usePrimListArray)
{
numPrimsInArray = scratchNode.numPrimitivesAndDoCollapse >> 1;
primArrayStartIndex = scratchNode.sortedPrimIndex;
nodeIndex = GetPrimRefIdx(FetchSortedPrimIndex(ShaderConstants.offsets.primIndicesSorted,
primArrayStartIndex),
numPrimRefs);
}
else
{
// Set the next node index to the head pointer of the range
nodeIndex = scratchNode.left_or_primIndex_or_instIndex;
}
}
isTri1 = false;
firstPairInRange = true;
}
GPU_ASSERT(IsLeafNode(nodeIndex, numPrimRefs));
const ScratchNode scratchNode = FetchScratchNode(scratchNodesScratchOffset, nodeIndex);
float3 v0 = scratchNode.bbox_min_or_v0;
float3 v1 = scratchNode.bbox_max_or_v1;
float3 v2 = scratchNode.sah_or_v2_or_instBasePtr;
uint primId = scratchNode.left_or_primIndex_or_instIndex;
uint geomId = ExtractScratchNodeGeometryIndex(scratchNode);
const bool isOpaque = IsOpaqueNode(scratchNode.packedFlags);
if (Settings.enableEarlyPairCompression)
{
if (IsScratchNodeQuadPrimitive(scratchNode))
{
const uint triangleIndex = isTri1 ? 1 : 0;
const TriangleData tri =
GetScratchNodeQuadVertices(scratchNodesScratchOffset, nodeIndex, triangleIndex);
v0 = tri.v0;
v1 = tri.v1;
v2 = tri.v2;
primId = GetScratchNodePrimitiveIndex(scratchNode, triangleIndex);
// Re-queue current node for extracting triangle 1.
rangeNextNode = isTri1 ? scratchNode.parent : nodeIndex;
}
else
{
rangeNextNode = scratchNode.parent;
}
}
else
{
if (usePrimListArray)
{
if ((currentIndexInArray + 1) == numPrimsInArray)
{
rangeNextNode = INVALID_IDX;
}
else
{
currentIndexInArray++;
rangeNextNode = GetPrimRefIdx(FetchSortedPrimIndex(ShaderConstants.offsets.primIndicesSorted,
primArrayStartIndex + currentIndexInArray),
numPrimRefs);
}
}
else
{
rangeNextNode = scratchNode.parent;
}
}
if (triPairDescCount == 0)
{
prefixSource = asuint(v0);
primIdAnchor = primId;
primIdDiff = 0;
geoIdAnchor = geomId;
geoIdDiff = 0;
planeDiffs = 0;
planeUnion = 0;
uniqueVertexCount = 0;
}
uint index0 = 0xFF;
uint index1 = 0xFF;
uint index2 = 0xFF;
uint3 diff0 = asuint(v0) ^ prefixSource;
uint3 diff1 = asuint(v1) ^ prefixSource;
uint3 diff2 = asuint(v2) ^ prefixSource;
// State used to generate the meshlet if triangle *cannot* be added
if (isTri1 == false)
{
planeDiffsBackup = planeDiffs;
uniqueVertexCountBackup = uniqueVertexCount;
primIdDiffBackup = primIdDiff;
geoIdDiffBackup = geoIdDiff;
triPairDescCountBackup = triPairDescCount;
planeUnionBackup = planeUnion;
firstNodeInPair = nodeIndex;
primIndexFirstInPair = currentIndexInArray - 1;
}
for (uint i = 0; i < uniqueVertexCount; i++)
{
index0 = (all(v0 == verts[i])) ? i : index0;
index1 = (all(v1 == verts[i])) ? i : index1;
index2 = (all(v2 == verts[i])) ? i : index2;
}
if (index0 == 0xFF)
{
index0 = uniqueVertexCount;
verts[index0] = v0;
planeDiffs = planeDiffs | diff0;
planeUnion = planeUnion | asuint(v0.x) | asuint(v0.y) | asuint(v0.z);
uniqueVertexCount++;
}
if (index1 == 0xFF)
{
index1 = uniqueVertexCount;
verts[index1] = v1;
planeDiffs = planeDiffs | diff1;
planeUnion = planeUnion | asuint(v1.x) | asuint(v1.y) | asuint(v1.z);
uniqueVertexCount++;
}
if (index2 == 0xFF)
{
index2 = uniqueVertexCount;
verts[index2] = v2;
planeDiffs = planeDiffs | diff2;
planeUnion = planeUnion | asuint(v2.x) | asuint(v2.y) | asuint(v2.z);
uniqueVertexCount++;
}
geoIdDiff |= (geoIdAnchor ^ geomId);
primIdDiff |= (primIdAnchor ^ primId);
bool pairDone = false;
if (isTri1)
{
GPU_ASSERT(triPairDescCount > 0);
pairDescs[triPairDescCount-1].InitTri1(
uint3(index0, index1, index2), isOpaque, primId, geomId);
// Last pair in the range
if (rangeNextNode == INVALID_IDX)
{
pairDescs[triPairDescCount-1].SetPrimRangeStopBit(true);
}
pairDone = true;
}
else
{
pairDescs[triPairDescCount].Init();
pairDescs[triPairDescCount].InitTri0(
uint3(index0, index1, index2), isOpaque, primId, geomId);
if (rangeNextNode == INVALID_IDX)
{
// No additional triangle to pair
pairDescs[triPairDescCount].InvalidateTri1();
pairDescs[triPairDescCount].SetPrimRangeStopBit(true);
pairDone = true;
}
triPairDescCount++;
}
const uint triPairIdx = triPairDescCount - 1;
const uint nodeType = (triPairIdx >= 4) ? (triPairIdx + 4) : triPairIdx;
if (pairDone == false)
{
// Wait until the full pair is setup before encoding
isTri1 = true;
continue;
}
isTri1 = false;
INIT_VAR(UnpackedPrimStructHeader, triStructHeader);
bool valid = TryInitTriStructHeader(asfloat(prefixSource),
planeDiffs,
planeUnion,
primIdDiff,
geoIdDiff,
primIdAnchor,
geoIdAnchor,
uniqueVertexCount,
triPairDescCount,
false,
enableTrailingZeroCompression,
triStructHeader);
if (triPairDescCount > maxPairs)
{
valid = false;
}
if (valid)
{
if (firstPairInRange)
{
// Update range of the last child
if (rangePacketCount > 0)
{
GPU_ASSERT(rangePacketCount < 16);
DstBuffer.InterlockedOr(lastValidChildInfoOffset, rangePacketCount << 28);
rangePacketCount = 0;
}
const uint childIdx = numBoxChildren + leafChildIdx;
// Update child type in the box node
const uint childInfoOffset =
parentBoxOffset +
QUANTIZED_BVH8_NODE_OFFSET_CHILD_INFO_0 +
(childIdx * QUANTIZED_NODE_CHILD_INFO_STRIDE) +
QUANTIZED_NODE_CHILD_INFO_OFFSET_MAXY_MAXZ_NODE_TYPE_AND_RANGE;
lastValidChildInfoOffset = childInfoOffset;
DstBuffer.InterlockedOr(childInfoOffset, nodeType << 24);
}
if (rangeNextNode == INVALID_NODE)
{
leafChildIdx++;
}
firstPairInRange = false;
}
else
{
valid = TryInitTriStructHeader(asfloat(prefixSource),
planeDiffsBackup,
planeUnionBackup,
primIdDiffBackup,
geoIdDiffBackup,
primIdAnchor,
geoIdAnchor,
uniqueVertexCountBackup,
triPairDescCountBackup,
false,
enableTrailingZeroCompression,
triStructHeader);
GPU_ASSERT(valid);
primStruct.Encode16(triStructHeader,
verts,
uniqueVertexCountBackup,
pairDescs,
triPairDescCountBackup,
primStructOffset);
const uint primStructIdx = IncrementAccelStructHeaderField(ACCEL_STRUCT_HEADER_NUM_LEAF_NODES_OFFSET, 1);
DstBuffer.Store(offsets.primNodePtrs + (primStructIdx * sizeof(uint)), primStructOffset);
rangePacketCount++;
triPairDescCount = 0;
// Reset back to the start of the pair that failed
rangeNextNode = firstNodeInPair;
if (usePrimListArray)
{
currentIndexInArray = primIndexFirstInPair;
}
primStructOffset += QBVH8::NodeSizeInBytes;
}
}
if (triPairDescCount > 0)
{
INIT_VAR(UnpackedPrimStructHeader, triStructHeader);
bool valid = TryInitTriStructHeader(asfloat(prefixSource),
planeDiffs,
planeUnion,
primIdDiff,
geoIdDiff,
primIdAnchor,
geoIdAnchor,
uniqueVertexCount,
triPairDescCount,
false,
enableTrailingZeroCompression,
triStructHeader);
GPU_ASSERT(valid);
primStruct.Encode16(triStructHeader,
verts,
uniqueVertexCount,
pairDescs,
triPairDescCount,
primStructOffset);
const uint primStructIdx = IncrementAccelStructHeaderField(ACCEL_STRUCT_HEADER_NUM_LEAF_NODES_OFFSET, 1);
DstBuffer.Store(offsets.primNodePtrs + (primStructIdx * sizeof(uint)), primStructOffset);
}
}
//=====================================================================================================================
static uint3 ComputePackedChildInfo(
in uint scratchNodesScratchOffset,
in ScratchNode childScratchNode,
in uint childScratchNodeIdx,
in uint nodeType,
in uint nodeRangeLength,
in float3 rcpExponents,
in float3 origin,
in uint numPrimRefs)
{
const bool isLeafNode = IsLeafNode(childScratchNodeIdx, numPrimRefs);
BoundingBox childBounds = GetScratchNodeBoundingBoxTS(scratchNodesScratchOffset, isLeafNode, childScratchNode);
const uint instanceMask =
ExtractScratchNodeInstanceMask(childScratchNode.packedFlags);
const uint boxNodeFlags =
ExtractScratchNodeBoxFlags(childScratchNode.packedFlags);
const uint3 childInfo = QBVH8::ComputePackedChildInfo(childBounds,
instanceMask,
boxNodeFlags,
nodeType,
nodeRangeLength,
rcpExponents,
origin);
return childInfo;
}
//=====================================================================================================================
// Write intersectable instance node as a filter node with 4 distinct child bounds sharing the same root node.
// This function prebuilds the filter node and stores it in the BLAS metadata. It is copied directly to the TLAS when
// an instance is not rebraided.
static void WriteBlasInstanceFilterNode(
in uint scratchNodesScratchOffset,
in uint numPrimRefs,
in uint rootNodeIndex,
in float3 origin,
in uint3 exponents,
in float3 rcpExponents)
{
// For single primitive case, skip building node array and just push the lone leaf node to
// the child node array
uint numBoxChildren = 0;
uint numLeafChildren = 0;
// For filter nodes, we just build 4 bounding boxes from the root node
const uint baseLdsOffset = GetNodeArrayBaseInLds(0, 4);
BuildChildNodeArray(0,
scratchNodesScratchOffset,
numPrimRefs,
rootNodeIndex,
4,
numBoxChildren,
numLeafChildren);
// The root of the BVH2 treelet contains the combined bounds of the child nodes in the node array.
// Compute the common exponent from the root node bounds
const uint validChildCount = numBoxChildren + numLeafChildren;
// Origin
const uint baseOffset = ACCEL_STRUCT_METADATA_INSTANCE_NODE_OFFSET;
DstMetadata.Store3(baseOffset, asuint(origin));
// Packed exponents, valid child count and child index in parent node
const uint packedExpChildIdxAndCount =
QuantizedBVH8BoxNode::PackExpChildIdxAndCount(exponents, 0, 0, 4);
DstMetadata.Store(baseOffset + QUANTIZED_BVH4_NODE_OFFSET_EXP_CHILD_IDX_AND_VALID_COUNT,
packedExpChildIdxAndCount);
for (uint i = 0; i < validChildCount; ++i)
{
const uint childScratchNodeIdx = SharedMem[baseLdsOffset + i];
const ScratchNode childScratchNode =
FetchScratchNode(scratchNodesScratchOffset, childScratchNodeIdx);
const bool isLeafNode = IsLeafNode(childScratchNodeIdx, numPrimRefs);
const BoundingBox childBounds =
GetScratchNodeBoundingBoxTS(scratchNodesScratchOffset, isLeafNode, childScratchNode);
const UintBoundingBox quantBounds = ComputeQuantizedBounds(childBounds, origin, rcpExponents, 12);
const uint3 childInfo = GetInstanceChildInfo(i, CreateRootNodePointer3_1(), quantBounds.min, quantBounds.max);
DstMetadata.Store3(baseOffset + GetBvh4ChildInfoOffset(i), childInfo);
}
// Encode remaining child slots as invalid
for (uint i = validChildCount; i < 4; ++i)
{
const uint3 childInfo = GetInstanceChildInfo(i, CreateRootNodePointer3_1(), 0xFFFFFFFF.xxx, 0.xxx);
DstMetadata.Store3(baseOffset + GetBvh4ChildInfoOffset(i), childInfo);
}
}
//=====================================================================================================================
// Box splitting / Child reuse
static void BoxSplitting(
LaneGroup laneGroup,
in uint scratchNodesScratchOffset,
in uint currNodeOffset,
in uint indexInParent,
in AccelStructOffsets offsets,
in uint baseLeafNodeOffset,
in uint maxNumChildren,
in uint numLeafChildren,
in uint numBoxChildren,
in uint boxOrLeafChildIndex,
in ScratchNode childScratchNode,
in uint numEmptySlots,
in float3 rcpExponents,
in uint3 exponents,
in BoundingBox parentBbox,
in bool isLeaf)
{
uint maxNodeLane = 0;
if (Settings.topLevelBuild && (numEmptySlots > 0) && (Settings.boxSplittingFlags & BoxSplittingFlags::Instance))
{
const NumPrimAndOffset numPrimAndOffset = LoadNumPrimAndOffset();
// Make sure the compressed box node is encoded
DeviceMemoryBarrier();
// Pick the instances in decreasing SAH order
if (isLeaf)
{
// Flag to indicate if the instance node in the current lane has been processed.
bool processed = false;
// Note, boxOrLeafChildIndex is only the index among the leaf children here.