summaryrefslogtreecommitdiffstats
path: root/tools/render-test/bind-location.cpp
blob: 4ec590fd5bc761ed223c2a803d2c4759fb3148d1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
#include "bind-location.h"

#include "../../slang-com-helper.h"

#include "../../source/core/slang-token-reader.h"

namespace renderer_test {
using namespace Slang;

/* static */const BindLocation BindLocation::Invalid;

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BindSet !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

BindSet::BindSet():
    m_arena(4096, 16)
{
}

BindSet::~BindSet()
{
    for (auto value : m_values)
    {
        value->~Value();
    }
}

void BindSet::setAt(const BindLocation& loc, Value* value)
{
    SLANG_ASSERT(loc.isValid());
    if (loc.isInvalid())
    {
        return;
    }

    // Note we don't remove when value == null, such that it is stored if should be nullptr
    Value** valuePtr = m_bindings.TryGetValueOrAdd(loc, value);
    if (valuePtr)
    {
        *valuePtr = value;
    }
}

void BindSet::setAt(const BindLocation& loc, SlangParameterCategory category, Value* value)
{
    SLANG_ASSERT(loc.isValid());
    if (loc.isInvalid())
    {
        return;
    }

    const BindPoint* point = loc.getValidBindPointForCategory(category);
    if (point)
    {
        if (loc.m_bindPointSet == nullptr)
        {
            // Can only have one category, so just set on that
            setAt(loc, value);
        }
        else
        {

            BindLocation catLoc(loc.m_typeLayout, category, *point, loc.m_value);
            setAt(catLoc, value);
        }
    }
    else
    {
        SLANG_ASSERT(!"Does not have category");
    }
}

BindSet::Value* BindSet::getAt(const BindLocation& loc) const
{
    SLANG_ASSERT(loc.isValid());
    if (loc.isInvalid())
    {
        return nullptr;
    }
    Value** valuePtr = m_bindings.TryGetValue(loc);
    return valuePtr ? *valuePtr : nullptr;
}

BindSet::Value* BindSet::_createBufferValue(slang::TypeReflection::Kind kind, slang::TypeLayoutReflection* typeLayout, size_t bufferSizeInBytes, size_t initialSizeInBytes, const void* initialData)
{
    SLANG_ASSERT(typeLayout == nullptr || typeLayout->getKind() == kind);

    Value* value = new (m_arena.allocateAligned(sizeof(Value), SLANG_ALIGN_OF(Value))) Value();

    value->m_kind = kind;
    value->m_sizeInBytes = bufferSizeInBytes;
    value->m_elementCount = 0;
    value->m_type = typeLayout;
    value->m_userIndex = -1;

    value->m_data = (uint8_t*)m_arena.allocateAligned(bufferSizeInBytes, 16);

    SLANG_ASSERT(initialSizeInBytes <= value->m_sizeInBytes);
    if (initialData)
    {
        ::memcpy(value->m_data, initialData, initialSizeInBytes);
        ::memset(value->m_data + initialSizeInBytes, 0, bufferSizeInBytes - initialSizeInBytes);
    }
    else
    {
        ::memset(value->m_data, 0, value->m_sizeInBytes);
    }

    m_values.add(value);
    return value;
}

/* static */bool BindSet::isTextureType(slang::TypeLayoutReflection* typeLayout)
{
    switch (typeLayout->getKind())
    {
        case slang::TypeReflection::Kind::Resource:
        {
            auto type = typeLayout->getType();
            auto shape = type->getResourceShape();

            switch (shape & SLANG_RESOURCE_BASE_SHAPE_MASK)
            {
                case SLANG_TEXTURE_2D:
                case SLANG_TEXTURE_1D:
                case SLANG_TEXTURE_3D:
                case SLANG_TEXTURE_CUBE:
                case SLANG_TEXTURE_BUFFER:
                {
                    return true;
                }
            }
        }
        default: break;
    }

    return false;
}

BindSet::Value* BindSet::createTextureValue(slang::TypeLayoutReflection* typeLayout)
{
    if (!isTextureType(typeLayout))
    {
        SLANG_ASSERT(!"Not a texture type");
        return nullptr;
    }

    Value* value = new (m_arena.allocateAligned(sizeof(Value), SLANG_ALIGN_OF(Value))) Value();

    value->m_kind = typeLayout->getKind();
    value->m_sizeInBytes = 0;
    value->m_elementCount = 0;
    value->m_type = typeLayout;
    value->m_data = nullptr;
    value->m_userIndex = -1;

    m_values.add(value);

    return value;
}

BindSet::Value* BindSet::createBufferValue(slang::TypeReflection::Kind kind, size_t sizeInBytes, const void* initialData)
{
    return _createBufferValue(kind, nullptr, sizeInBytes, sizeInBytes, initialData);
}

BindSet::Value* BindSet::createBufferValue(slang::TypeLayoutReflection* typeLayout, size_t sizeInBytes, const void* initialData)
{
    const auto kind = typeLayout->getKind();
    switch (kind)
    {
        case slang::TypeReflection::Kind::ParameterBlock:
        case slang::TypeReflection::Kind::ConstantBuffer:
        {
            return _createBufferValue(kind, typeLayout, sizeInBytes, sizeInBytes, initialData);
        }
        case slang::TypeReflection::Kind::Resource:
        {
            auto type = typeLayout->getType();
            auto shape = type->getResourceShape();

            switch (shape & SLANG_RESOURCE_BASE_SHAPE_MASK)
            {
                case SLANG_STRUCTURED_BUFFER:
                {
                    auto elementTypeLayout = typeLayout->getElementTypeLayout();
                    size_t elementSize = elementTypeLayout->getSize(SLANG_PARAMETER_CATEGORY_UNIFORM);

                    // We don't know the size of the buffer, but we can work it out, based on what is initialized
                    size_t elementCount = size_t((sizeInBytes + elementSize - 1) / elementSize);
                    size_t bufferSize = elementCount * elementSize;

                    Value* value = _createBufferValue(kind, typeLayout, bufferSize, sizeInBytes, initialData);
                    value->m_elementCount = elementCount;
                    return value;
                }
                case SLANG_BYTE_ADDRESS_BUFFER:
                {
                    return _createBufferValue(kind, typeLayout,  (sizeInBytes + 3) & ~size_t(3), sizeInBytes, initialData);
                }
            }
            break;
        }


        default: break;
    }

    SLANG_ASSERT(!"Unable to construct this type of buffer");
    return nullptr;
}

void BindSet::destroyValue(Value* value)
{
    // TODO(JS): NOTE we do not free the old buffer. This is not a memory leak, because
    // it is tracked elsewhere, but there is an argument to destroy it.
    const Index index = m_values.indexOf(value);
    SLANG_ASSERT(index >= 0);
    if (index >= 0)
    {
        m_values.fastRemoveAt(index);

        // I guess we should remove any bindings to it whilst we are at it
        List<BindLocation> locations;
        for (const auto& pair : m_bindings)
        {
            const auto& location = pair.Key;
            if (location.m_value == value)
            {
                locations.add(location);
            }
        }

        for (auto location : locations)
        {
            m_bindings.Remove(location);
        }

        // Run the dtor
        value->~Value();
    }
}

void BindSet::calcChildResourceLocations(const BindLocation& location, List<BindLocation>& outLocations)
{
    auto typeLayout = location.getTypeLayout();

    const auto kind = typeLayout->getKind();
    switch (kind)
    {
        case slang::TypeReflection::Kind::Array:
        {
            auto elementTypeLayout = typeLayout->getElementTypeLayout(); 
            auto elementCount = int(typeLayout->getElementCount());

            // We only iterate over the array, if it's a fixed array (not an unbounded array)
            // as it is then the elements are much like the fields of a struct and so 'children'.
            if (elementCount != 0)
            {
                for (Index i = 0; i < elementCount; ++i)
                {
                    BindLocation elementLocation = toIndex(location, i);
                    calcChildResourceLocations(elementLocation, outLocations);
                }
            }
            break;
        }
        case slang::TypeReflection::Kind::Struct:
        {
            auto structTypeLayout = typeLayout;

            auto fieldCount = structTypeLayout->getFieldCount();
            for (uint32_t ff = 0; ff < fieldCount; ++ff)
            {
                auto field = structTypeLayout->getFieldByIndex(ff);
                BindLocation fieldLocation = toField(location, field);

                calcChildResourceLocations(fieldLocation, outLocations);
            }
            break;
        }

        default: break;
    }
}

void BindSet::calcValueLocations(const BindLocation& location, Slang::List<BindLocation>& outLocations)
{
    auto typeLayout = location.getTypeLayout();

    const auto kind = typeLayout->getKind();
    switch (kind)
    {
        case slang::TypeReflection::Kind::Array:
        {
            auto elementTypeLayout = typeLayout->getElementTypeLayout();
            auto elementCount = int(typeLayout->getElementCount());

            // If it's unbounded, it could point directly to a value/resource. We can't iterate over it
            // as 'children' because being an external value/resource (or in a register space) they
            // are not part of the underling location. 
            if (elementCount == 0)
            {
                outLocations.add(location);
            }
            break;
        }

        case slang::TypeReflection::Kind::SamplerState:

        case slang::TypeReflection::Kind::ParameterBlock:
        case slang::TypeReflection::Kind::ConstantBuffer:
        case slang::TypeReflection::Kind::Resource:
        case slang::TypeReflection::Kind::TextureBuffer:
        case slang::TypeReflection::Kind::ShaderStorageBuffer:
        {
            //auto elementTypeLayout = typeLayout->getElementTypeLayout();
            //const size_t elementSize = elementTypeLayout->getSize();

            outLocations.add(location);
            break;
        }
        default:
        {
            calcChildResourceLocations(location, outLocations);
            break;
        }
    }
}

BindLocation BindSet::toField(const BindLocation& loc, slang::VariableLayoutReflection* field) const
{
    const Index categoryCount = Index(field->getCategoryCount());
    if (categoryCount == 0)
    {
        return BindLocation::Invalid;
    }

    if (loc.m_bindPointSet)
    {
        BindPoints bindPoints;
        bindPoints.setInvalid();

        // Copy over and add the ones found here
        for (Index i = 0; i < categoryCount; ++i)
        {
            auto category = field->getCategoryByIndex((unsigned int)i);

            auto const& point = loc.m_bindPointSet->m_points[category];
            if (point.isInvalid())
            {
                return BindLocation::Invalid;
            }

            auto space = field->getBindingSpace(category);
            auto offset = field->getOffset(category);

            // Set using new space, and offset
            bindPoints[category] = BindPoint(space, point.m_offset + offset);
        }

        return BindLocation(field->getTypeLayout(), bindPoints, loc.m_value);
    }
    else
    {
        SLANG_ASSERT(categoryCount == 1);
        auto category = field->getCategoryByIndex(0);

        // If I'm going from mixed, then I will have multiple items being tracked (so won't be here)
        // If I'm not, then I'm getting an inplace field. It must be relative
        // So it would seem I never need to call getBindingIndex, and since I can't do that it must be relative.
        // AND if it's relative well it must be in the same category.
      
        if (category == loc.m_category)
        {
            auto space = field->getBindingSpace(category);
            auto offset = field->getOffset(category);

            return BindLocation(field->getTypeLayout(), category, BindPoint(space, loc.m_point.m_offset + offset), loc.m_value);
        }
    }

    return BindLocation::Invalid;
}

BindLocation BindSet::toField(const BindLocation& loc, const char* name) const
{
    if (!loc.isValid())
    {
        return loc;
    }

    auto typeLayout = loc.m_typeLayout;
    const auto kind = typeLayout->getKind();

    // Strip constantBuffer wrapping, only really applies when we have handles to value/resource
    // embedded in other types (like on CPU and CUDA)
    if (loc.m_value &&
        (kind == slang::TypeReflection::Kind::ConstantBuffer || kind == slang::TypeReflection::Kind::ParameterBlock))
    {
        // Follow the to associated value/resource
        BindSet::Value* value = getAt(loc);
        if (value)
        {
            typeLayout = typeLayout->getElementTypeLayout();
            return toField(BindLocation(typeLayout, SLANG_PARAMETER_CATEGORY_UNIFORM, BindPoint(0, 0), value), name);
        }
    }

    if (kind == slang::TypeReflection::Kind::Struct)
    {
        slang::VariableLayoutReflection* varLayout = nullptr;
        auto fieldCount = typeLayout->getFieldCount();
        for (uint32_t ff = 0; ff < fieldCount; ++ff)
        {
            auto field = typeLayout->getFieldByIndex(ff);
            if (strcmp(field->getName(), name) == 0)
            {
                return toField(loc, field);
            }
        }
    }

    // Invalid
    return BindLocation::Invalid; 
}

BindLocation BindSet::toIndex(const BindLocation& loc, Index index) const
{
    if (!loc.isValid())
    {
        return loc;
    }
    SLANG_ASSERT(index >= 0);
    if (index < 0)
    {
        return BindLocation::Invalid;
    }

    auto typeLayout = loc.m_typeLayout;
    const auto kind = typeLayout->getKind();

    // If it's a zero sized array, we may need to special case indirecting through a buffer that holds it's contents
    if (kind != slang::TypeReflection::Kind::Array)
    {
        return BindLocation::Invalid;
    }

    // Find where the uniform data will be held. If we have a unsized array, for some targets the actual content's might be in a different location
    BindSet::Value* uniformValue = loc.m_value;
    if (typeLayout->getElementCount() == 0)
    {
        // If we have a value/resource at this location, then we need to offset through that
        BindSet::Value* arrayValue = getAt(loc);
        if (arrayValue)
        {
            uniformValue = arrayValue;

            // Check it's in range.
            // NOTE we can't check this if the unbounded binding is in another space for example. 
            if (index >= Index(uniformValue->m_elementCount))
            {
                return BindLocation::Invalid;
            }
        }
    }

    auto elementTypeLayout = typeLayout->getElementTypeLayout();

    const Index categoryCount = Index(elementTypeLayout->getCategoryCount());

    if (loc.m_bindPointSet)
    {
        BindPoints bindPoints;
        bindPoints.setInvalid();

        // Copy over and add the ones found here
        for (Index i = 0; i < categoryCount; ++i)
        {
            auto category = elementTypeLayout->getCategoryByIndex((unsigned int)i);
            const auto elementStride = typeLayout->getElementStride(category);

            size_t baseOffset = loc.m_bindPointSet->m_points[category].m_offset;

            if (category == slang::ParameterCategory::Uniform && uniformValue != loc.m_value)
            {
                baseOffset = 0;
            }
             
            const auto& basePoint = loc.m_bindPointSet->m_points[category];
            SLANG_ASSERT(basePoint.isValid());
            bindPoints[category] = BindPoint(basePoint.m_space, baseOffset + elementStride * index);
        }

        return BindLocation(elementTypeLayout, bindPoints, uniformValue);
    }
    else
    {
        SLANG_ASSERT(categoryCount == 1);
        auto category = elementTypeLayout->getCategoryByIndex(0);

        const auto elementStride = typeLayout->getElementStride(category);

        size_t baseOffset = 0;
        if (category == slang::ParameterCategory::Uniform && uniformValue != loc.m_value)
        {
            // base of 0 is appropriate as it is the child value
        }
        else
        {
            // TODO(JS): 
            // Hmm, if its a different category, then not entirely clear what to do here.
            // Just zero as we can't use the base we have.
            // This might just be an error

            baseOffset = (category == loc.m_category) ? loc.m_point.m_offset : 0;
        }

        BindPoint point(loc.m_point.m_space, baseOffset + elementStride * index);

        return BindLocation(elementTypeLayout, category, point, uniformValue);
    }

    return BindLocation::Invalid;
}


SlangResult BindSet::setBufferContents(const BindLocation& loc, const void* initialData, size_t sizeInBytes) const
{
    BindSet::Value* value = getAt(loc);
    if (value)
    {
        // Truncate if initial data is larger than the buffer
        sizeInBytes = (sizeInBytes > value->m_sizeInBytes) ? value->m_sizeInBytes : sizeInBytes;

        SLANG_ASSERT(value->m_sizeInBytes >= sizeInBytes);
        ::memcpy(value->m_data, initialData, sizeInBytes);
        return SLANG_OK;
    }
    return SLANG_FAIL;
}

void BindSet::getBindings(List<BindLocation>& outLocations, List<Value*>& outResources) const
{
    outResources.clear();
    outLocations.clear();
    for (const auto& pair : m_bindings)
    {
        outLocations.add(pair.Key);
        outResources.add(pair.Value);
    }
}

void BindSet::releaseValueTargets()
{
    for (Value* value : m_values)
    {
        value->m_target.setNull();
    }
}

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BindLocation !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

BindLocation::BindLocation(slang::TypeLayoutReflection* typeLayout, const BindPoints& points, BindSet_Value* value) :
    m_typeLayout(typeLayout),
    m_value(value)
{
    setPoints(points);
}

BindLocation::BindLocation(slang::TypeLayoutReflection* typeLayout, SlangParameterCategory category, const BindPoint& point, BindSet_Value* value) :
    m_category(category),
    m_point(point),
    m_typeLayout(typeLayout),
    m_value(value)
{
}

BindLocation::BindLocation(slang::VariableLayoutReflection* varLayout, BindSet_Value* value)
{    
    m_value = value;
    m_typeLayout = varLayout->getTypeLayout();

    const Index categoryCount = Index(varLayout->getCategoryCount());

    if (categoryCount <= 0)
    {
        *this = BindLocation::Invalid;
        return;
    }
    else if (categoryCount == 1)
    {
        const auto category = varLayout->getCategoryByIndex(0);

        const auto offset = varLayout->getOffset(category);
        const auto space = varLayout->getBindingSpace(category);

        m_category = category;
        m_point = BindPoint(Index(space), size_t(offset));
    }
    else
    {
        BindPoints points;
        points.setInvalid();

        for (Index i = 0; i < categoryCount; ++i)
        {
            const auto category = varLayout->getCategoryByIndex((unsigned int)i);

            const auto offset = varLayout->getOffset(category);
            const auto space = varLayout->getBindingSpace(category);

            BindPoint& point = points.m_points[category];

            point.m_offset = size_t(offset);
            point.m_space = Index(space);
        }

        setPoints(points);
    }
}

BindPoint* BindLocation::getValidBindPointForCategory(SlangParameterCategory category)
{
    BindPoint* point = nullptr;
    if (m_bindPointSet)
    {
         point = &m_bindPointSet->m_points.m_points[category];
    }
    else if (m_category == category)
    {
        point = &m_point;
    }
    return (point && point->isValid()) ? point : nullptr;
}

const BindPoint* BindLocation::getValidBindPointForCategory(SlangParameterCategory category) const
{
    const BindPoint* point = nullptr;
    if (m_bindPointSet)
    {
        point = &m_bindPointSet->m_points.m_points[category];
    }
    else if (m_category == category)
    {
        point = &m_point;
    }
    return (point && point->isValid()) ? point : nullptr;
}

BindPoint BindLocation::getBindPointForCategory(SlangParameterCategory category) const
{
    if (m_bindPointSet)
    {
        return m_bindPointSet->m_points.m_points[category];
    }
    else if (m_category == category)
    {
        return m_point;
    }
    return BindPoint::makeInvalid();
}

void BindLocation::setPoints(const BindPoints& points)
{
    Index found;
    auto const validCount = points.calcValidCount(&found);

    // There is nothing tracked, so we are done.
    if (validCount == 0)
    {
        setEmptyBinding();
        return;
    }

    if (validCount == 1)
    {
        m_bindPointSet.setNull();
        m_point = points.m_points[found];
        m_category = SlangParameterCategory(found);
        return;
    }

    if (m_bindPointSet->isUniquelyReferenced())
    {
        m_bindPointSet->m_points = points;
    }
    else
    {
        m_bindPointSet = new BindPointSet(points);
    }
}

void BindLocation::addOffset(SlangParameterCategory category, ptrdiff_t offset)
{
    BindPoint* point = getValidBindPointForCategory(category);
    if (point)
    {
        point->m_offset += offset;
    }
}

void* BindLocation::getUniform(size_t sizeInBytes) const
{
    const BindPoint* point = getValidBindPointForCategory(SLANG_PARAMETER_CATEGORY_UNIFORM);
    if (m_value && point)
    {
        size_t offset = point->m_offset;
        // Make sure it's in range
        if (offset + sizeInBytes <= m_value->m_sizeInBytes)
        {
            return m_value->m_data + offset;
        }
    }
    return nullptr;
}

SlangResult BindLocation::setUniform(const void* data, size_t sizeInBytes) const
{
    // It has to be a location with uniform
    const BindPoint* point = getValidBindPointForCategory(SLANG_PARAMETER_CATEGORY_UNIFORM);
    if (m_value && point)
    {
        size_t offset = point->m_offset;
        ptrdiff_t maxSizeInBytes = m_value->m_sizeInBytes - offset;
        SLANG_ASSERT(maxSizeInBytes > 0);

        if (maxSizeInBytes <= 0)
        {
            return SLANG_FAIL;
        }

        // Clamp such that only fill in what's available to write
        sizeInBytes = sizeInBytes > size_t(maxSizeInBytes) ? size_t(maxSizeInBytes) : sizeInBytes;

        // Make sure it's in range
        SLANG_ASSERT(offset + sizeInBytes <= m_value->m_sizeInBytes);

        // Okay copy the contents
        ::memcpy(m_value->m_data + offset, data, sizeInBytes);
        return SLANG_OK;
    }
    return SLANG_FAIL;
}

bool BindLocation::operator==(const ThisType& rhs) const
{
    if (m_typeLayout != rhs.m_typeLayout ||
        m_value != rhs.m_value)
    {
        return false;
    }

    // If same, then if it's set they must be equal
    // If not set, then must be the same category/point
    if (m_bindPointSet == rhs.m_bindPointSet)
    {
        return m_bindPointSet || (m_category == rhs.m_category && m_point == rhs.m_point);
    }

    // Only way these can be equal now, is if both are m_bindPointSet are different pointers, but same value
    return (m_bindPointSet && rhs.m_bindPointSet) && (m_bindPointSet->m_points == rhs.m_bindPointSet->m_points);
}

HashCode BindLocation::getHashCode() const
{
    if (!m_typeLayout)
    {
        return 1;
    }
    if (m_bindPointSet)
    {
        return m_bindPointSet->getHashCode();
    }
    else
    {
        return Slang::combineHash(Slang::combineHash(m_category, Slang::getHashCode(m_typeLayout)), m_point.getHashCode());
    }
}


// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BindRoot !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

SlangResult BindRoot::parse(const String& text, const String& sourcePath, WriterHelper outStream, BindLocation& outLocation)
{
    SLANG_ASSERT(m_bindSet);

    // We will parse the 'name' as may be path to a value/resource
    TokenReader parser(text);

    BindLocation location = BindLocation::Invalid; 

    {
        Token nameToken = parser.ReadToken();
        if (nameToken.Type != TokenType::Identifier)
        {
            outStream.print("Invalid input syntax at line %d", int(parser.NextToken().Position.Line));
            return SLANG_FAIL;
        }
        location = find(nameToken.Content.getBuffer());
        if (location.isInvalid())
        {
            outStream.print("Unable to find entry in '%s' for '%s' (for CPU name must be specified) \n", sourcePath.getBuffer(), text.getBuffer());
            return SLANG_FAIL;
        }
    }

    while (!parser.IsEnd())
    {
        Token token = parser.NextToken(0);

        if (token.Type == TokenType::LBracket)
        {
            parser.ReadToken();
            int index = parser.ReadInt();
            SLANG_ASSERT(index >= 0);

            location = m_bindSet->toIndex(location, index);
            if (location.isInvalid())
            {
                outStream.print("Unable to find entry in '%d' in '%s'\n", index, text.getBuffer());
                return SLANG_FAIL;
            }
            parser.ReadMatchingToken(TokenType::RBracket);
        }
        else if (token.Type == TokenType::Dot)
        {
            parser.ReadToken();
            Token identifierToken = parser.ReadMatchingToken(TokenType::Identifier);

            location = m_bindSet->toField(location, identifierToken.Content.getBuffer());
            if (location.isInvalid())
            {
                outStream.print("Unable to find field '%s' in '%s'\n", identifierToken.Content.getBuffer(), text.getBuffer());
                return SLANG_FAIL;
            }
        }
        else if (token.Type == TokenType::Comma)
        {
            // Break out
            break;
        }
        else
        {
           return SLANG_FAIL;
        }
    }

    outLocation = location;
    return SLANG_OK;
}

slang::VariableLayoutReflection* BindRoot::getParameterByName(const char* name)
{
    const int parameterCount = m_reflection->getParameterCount();
    for (int i = 0; i < parameterCount; ++i)
    {
        auto parameter = m_reflection->getParameterByIndex(i);
        const char* paramName = parameter->getName();
        if (strcmp(name, paramName) == 0)
        {
            return parameter;
        }
    }

    return nullptr;
}

slang::VariableLayoutReflection* BindRoot::getEntryPointParameterByName(const char* name)
{
    const int parameterCount = int(m_entryPoint->getParameterCount());
    for (int i = 0; i < parameterCount; ++i)
    {
        auto parameter = m_entryPoint->getParameterByIndex(i);
        // If has a semantic we will ignore
        if (parameter->getSemanticName())
        {
            continue;
        }
        if (strcmp(parameter->getName(), name) == 0)
        {
            return parameter;
        }
    }
    return nullptr;
}

SlangResult BindRoot::init(BindSet* bindSet, slang::ShaderReflection* reflection, int entryPointIndex)
{
    m_bindSet = bindSet;
    m_reflection = reflection;
    m_entryPoint = nullptr;
    
    {
        auto entryPointCount = int(reflection->getEntryPointCount());
        if (entryPointIndex < 0 || entryPointIndex >= entryPointCount)
        {
            SLANG_ASSERT(!"Entry point index out of range");
            return SLANG_FAIL;
        }
        m_entryPoint = reflection->getEntryPointByIndex(entryPointIndex);
    }

    return SLANG_OK;
}

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! CPULikeBindRoot !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

SlangResult CPULikeBindRoot::init(BindSet* bindSet, slang::ShaderReflection* reflection, int entryPointIndex)
{
    m_rootValue = nullptr;
    m_entryPointValue = nullptr;

    SLANG_RETURN_ON_FAIL(Super::init(bindSet, reflection, entryPointIndex));

    {
        size_t globalConstantBuffer = reflection->getGlobalConstantBufferSize();

        size_t rootSizeInBytes = 0;
        const int parameterCount = reflection->getParameterCount();
        for (int i = 0; i < parameterCount; ++i)
        {
            auto parameter = reflection->getParameterByIndex(i);

            auto offset = parameter->getOffset();

            auto typeLayout = parameter->getTypeLayout();
            auto sizeInBytes = typeLayout->getSize();

            size_t endOffset = offset + sizeInBytes;

            rootSizeInBytes = (endOffset > rootSizeInBytes) ? endOffset : rootSizeInBytes;
        }
        SLANG_ASSERT(rootSizeInBytes == globalConstantBuffer);

        if (rootSizeInBytes)
        {
            // Allocate the 'root' buffer
            m_rootValue = m_bindSet->createBufferValue(slang::TypeReflection::Kind::ConstantBuffer, rootSizeInBytes);
        }
    }

    {
        size_t entryPointParamsSizeInBytes = 0;

        const int parameterCount = int(m_entryPoint->getParameterCount());
        for (int i = 0; i < parameterCount; i++)
        {
            slang::VariableLayoutReflection* parameter = m_entryPoint->getParameterByIndex(i);

            // If has a semantic, then isn't uniform parameter
            if (auto semanticName = parameter->getSemanticName())
            {
                continue;
            }

            auto offset = parameter->getOffset();

            auto typeLayout = parameter->getTypeLayout();
            auto sizeInBytes = typeLayout->getSize();

            size_t endOffset = offset + sizeInBytes;
            entryPointParamsSizeInBytes = (endOffset > entryPointParamsSizeInBytes) ? endOffset : entryPointParamsSizeInBytes;
        }

        if (entryPointParamsSizeInBytes)
        {
            m_entryPointValue = m_bindSet->createBufferValue(slang::TypeReflection::Kind::ConstantBuffer, entryPointParamsSizeInBytes);
        }
    }

    return SLANG_OK;
}



BindLocation CPULikeBindRoot::find(const char* name)
{
    Value* value = nullptr;
    slang::VariableLayoutReflection* varLayout = nullptr;

    if (m_rootValue)
    {
        varLayout = getParameterByName(name);
        value = m_rootValue;
    }
        
    if (!varLayout && m_entryPointValue)
    {
        value = m_entryPointValue;
        varLayout = getEntryPointParameterByName(name);
    }

    if (!varLayout)
    {
        return BindLocation::Invalid;
    }

    // We don't need to worry about bindSpace because variable must be stored in the buffer 
    // auto space = varLayout->getBindingSpace();
    // TODO(JS): Where is getBindingIndex supposed to be used. It seems the offset here will do the right thing
    auto offset = varLayout->getOffset(SLANG_PARAMETER_CATEGORY_UNIFORM);

    return BindLocation(varLayout->getTypeLayout(), SLANG_PARAMETER_CATEGORY_UNIFORM, BindPoint(0, offset), value);
}

SlangResult CPULikeBindRoot::setArrayCount(const BindLocation& location, int count)
{
    if (!location.isValid())
    {
        return SLANG_FAIL;
    }

    // I can see if a resource has already been set
    Value* value = m_bindSet->getAt(location);
    
    auto typeLayout = location.getTypeLayout();
    const auto kind = typeLayout->getKind();

    if (!(typeLayout->getKind() == slang::TypeReflection::Kind::Array && typeLayout->getElementCount() == 0))
    {
        return SLANG_FAIL;
    }

    const size_t elementStride = typeLayout->getElementStride(SLANG_PARAMETER_CATEGORY_UNIFORM);
    auto elementTypeLayout = typeLayout->getElementTypeLayout();

    if (value)
    {
        // Making smaller, just reduce the count.
        // NOTE! Nothing is done here about deallocating resources which are perhaps no longer reachable.
        // This isn't a leakage problem tho, as all buffers are released automatically when scope is left.
        if (count <= int(value->m_elementCount) || count <= int(value->m_sizeInBytes / elementStride))
        {
            value->m_elementCount = count;
            return SLANG_OK;
        }

        const size_t maxElementCount = (value->m_sizeInBytes / elementStride);
        if (size_t(count) <= maxElementCount)
        {
            // Just initialize the space
            ::memset(value->m_data + elementStride * value->m_elementCount, 0, (count - value->m_elementCount) * elementStride);
            value->m_elementCount = count;
            return SLANG_OK;
        }
    }

    // Ok allocate a buffer that can hold all the elements
    
    const size_t newBufferSize = count * elementStride;

    Value* newValue = m_bindSet->createBufferValue(slang::TypeReflection::Kind::Array, newBufferSize);
    newValue->m_elementCount = count;

    // Copy over the data from the old buffer if there is any
    if (value && value->m_elementCount)
    {
        ::memcpy(newValue->m_data, value->m_data, value->m_elementCount * elementStride);
    }

    // Remove the old buffer as no longer needed

    if (value)
    {
        m_bindSet->destroyValue(value);
    }

    // Set the new buffer
    m_bindSet->setAt(location, newValue);
    return SLANG_OK;
}


void CPULikeBindRoot::getRoots(Slang::List<BindLocation>& outLocations)
{
    if (m_entryPointValue)
    {
        const int parameterCount = int(m_entryPoint->getParameterCount());
        for (int i = 0; i < parameterCount; ++i)
        {
            auto parameter = m_entryPoint->getParameterByIndex(i);
            // If has a semantic we will ignore
            if (parameter->getSemanticName())
            {
                continue;
            }

            auto offset = parameter->getOffset(SLANG_PARAMETER_CATEGORY_UNIFORM);

            BindLocation location(parameter->getTypeLayout(), SLANG_PARAMETER_CATEGORY_UNIFORM, BindPoint(0, offset), m_entryPointValue);
            outLocations.add(location);
        }
    }

    if (m_rootValue)
    {
        const int parameterCount = m_reflection->getParameterCount();
        for (int i = 0; i < parameterCount; ++i)
        {
            auto parameter = m_reflection->getParameterByIndex(i);

            auto offset = parameter->getOffset(SLANG_PARAMETER_CATEGORY_UNIFORM);

            BindLocation location(parameter->getTypeLayout(), SLANG_PARAMETER_CATEGORY_UNIFORM, BindPoint(0, offset), m_rootValue);
            outLocations.add(location);
        }
    }
}

static void _addDefaultBuffersRec(BindSet* bindSet, const BindLocation& loc)
{
    // See if there is a value/resource attached there
    auto typeLayout = loc.getTypeLayout();

    const auto kind = typeLayout->getKind();
    switch (kind)
    {   
        case slang::TypeReflection::Kind::ParameterBlock:
        case slang::TypeReflection::Kind::ConstantBuffer:
        {
            BindSet::Value* value = bindSet->getAt(loc);

            auto elementTypeLayout = typeLayout->getElementTypeLayout();

            if (!value)
            {
                //SLANG_ASSERT(typeLayout->getSize() == sizeof(void*));
                const size_t elementSize = elementTypeLayout->getSize();

                // We create using typeLayout (as opposed to elementTypeLayout), because it also holds the wrapping
                // 'resource' type.
                value = bindSet->createBufferValue(typeLayout, elementSize);
                SLANG_ASSERT(value);

                bindSet->setAt(loc, value);
            }

            // Recurse into buffer, using the elementType
            BindLocation childLocation(elementTypeLayout, SLANG_PARAMETER_CATEGORY_UNIFORM, BindPoint(0, 0), value );
            _addDefaultBuffersRec(bindSet, childLocation);
            return;
        }
        default: break;    
    }

    // Recurse
    {
        List<BindLocation> childLocations;
        bindSet->calcChildResourceLocations(loc, childLocations);
        for (auto& childLocation : childLocations)
        {
            _addDefaultBuffersRec(bindSet, childLocation);
        }
    }
}

void CPULikeBindRoot::addDefaultValues()
{

    List<BindLocation> rootLocations;
    getRoots(rootLocations);

    for (auto& location : rootLocations)
    {
        _addDefaultBuffersRec(m_bindSet, location);
    }
}

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! GPULikeBindRoot !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

BindLocation GPULikeBindRoot::find(const char* name)
{
    slang::VariableLayoutReflection* varLayout = nullptr;

    varLayout = getParameterByName(name);
    if (!varLayout)
    {
        varLayout = getEntryPointParameterByName(name);
    }

    if (!varLayout)
    {
        return BindLocation::Invalid;
    }

    return BindLocation(varLayout, nullptr);
}

SlangResult GPULikeBindRoot::setArrayCount(const BindLocation& location, int count)
{
    // TODO(JS):
    // Not 100% clear how to handle this. If the mechanism uses 'spaces' there is nothing to do.
    // If the size is an aspect of the binding, then we need to set up the binding information correctly. Depending on underlying
    // API. This could perhaps be handled with a base class for m_target which meant we could just call that and it would
    // do the right thing.
    //
    // For now, lets not worry.
    return SLANG_OK;
}

void GPULikeBindRoot::getRoots(Slang::List<BindLocation>& outLocations)
{
    {
        const int parameterCount = int(m_entryPoint->getParameterCount());
        for (int i = 0; i < parameterCount; ++i)
        {
            auto parameter = m_entryPoint->getParameterByIndex(i);
            // If has a semantic we will ignore
            if (parameter->getSemanticName())
            {
                continue;
            }

            auto offset = parameter->getOffset(SLANG_PARAMETER_CATEGORY_UNIFORM);

            BindLocation location(parameter, nullptr);
            SLANG_ASSERT(location.isValid());

            outLocations.add(location);
        }
    }
    {
        const int parameterCount = m_reflection->getParameterCount();
        for (int i = 0; i < parameterCount; ++i)
        {
            auto parameter = m_reflection->getParameterByIndex(i);

            BindLocation location(parameter, nullptr);
            SLANG_ASSERT(location.isValid());

            outLocations.add(location);
        }
    }
}

} // renderer_test