File: dx12_experimental_resource_value_tracker.cpp

package info (click to toggle)
gfxreconstruct 0.9.18%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 24,636 kB
  • sloc: cpp: 328,961; ansic: 25,454; python: 18,156; xml: 255; sh: 128; makefile: 6
file content (654 lines) | stat: -rw-r--r-- 29,860 bytes parent folder | download
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
/*
** Copyright (c) 2022 LunarG, Inc.
** Copyright (c) 2022 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.
*/

#include "decode/dx12_experimental_resource_value_tracker.h"

#include "decode/custom_dx12_struct_decoders.h"

#include <algorithm>
#include <map>

GFXRECON_BEGIN_NAMESPACE(gfxrecon)
GFXRECON_BEGIN_NAMESPACE(decode)

bool Dx12ExperimentalResourceValueTracker::AddTrackedResourceValue(format::HandleId              resource_id,
                                                                   ResourceValueType             type,
                                                                   uint64_t                      offset,
                                                                   const uint8_t*                resource_value_data,
                                                                   const graphics::Dx12GpuVaMap& gpu_va_map)
{
    bool success =
        Dx12ResourceValueTracker::AddTrackedResourceValue(resource_id, type, offset, resource_value_data, gpu_va_map);

    if (!success && track_unassociated_values_)
    {
        uint64_t block_index                  = get_current_block_index_func_();
        auto&    unassociated_resource_values = unassociated_resource_values_[resource_id];
        GFXRECON_ASSERT(unassociated_resource_values.empty() ||
                        (block_index >= unassociated_resource_values.back().block_index));

        if (unassociated_resource_values.empty() || (block_index > unassociated_resource_values.back().block_index))
        {
            unassociated_resource_values.push_back({ block_index, {} });
        }
        auto& values_group = unassociated_resource_values.back();

        Dx12UnassociatedResourceValue unassociated_value;
        unassociated_value.type = type;

        if (type == ResourceValueType::kShaderIdentifier)
        {
            unassociated_value.shader_id = graphics::PackDx12ShaderIdentifier(resource_value_data);
        }
        else if (type == ResourceValueType::kGpuVirtualAddress)
        {
            auto     referenced_resource_id = format::kNullHandleId;
            bool     found_resource_id      = false;
            uint64_t old_address;
            util::platform::MemoryCopy(&old_address, 8, resource_value_data, 8);
            gpu_va_map.Map(old_address, &referenced_resource_id, &found_resource_id);
            if (found_resource_id)
            {
                unassociated_value.resource_id = referenced_resource_id;
            }
            else
            {
                GFXRECON_LOG_ERROR("Failed to find the resource for an unassociated resource GPU VA (address=%" PRIu64
                                   ").",
                                   old_address);
            }
        }

        values_group.values.push_back(std::move(unassociated_value));
    }

    return success;
}

void Dx12ExperimentalResourceValueTracker::GetTrackedResourceValues(Dx12FillCommandResourceValueMap& tracked_values)
{
    Dx12ResourceValueTracker::GetTrackedResourceValues(tracked_values);

    if (resolve_unassociated_values_)
    {
        for (auto& non_dxr_ranges_pair : non_dxr_fill_command_data_)
        {
            auto block_index                = non_dxr_ranges_pair.first;
            auto block_resource_values_iter = tracked_values.find(block_index);
            if (block_resource_values_iter != tracked_values.end())
            {
                for (auto& non_dxr_range : non_dxr_ranges_pair.second)
                {
                    auto& res_vals   = block_resource_values_iter->second;
                    auto  min_offset = non_dxr_range.first;
                    auto  max_offset = non_dxr_range.second;
                    auto  end_iter =
                        std::remove_if(res_vals.begin(),
                                       res_vals.end(),
                                       [min_offset, max_offset](const Dx12FillCommandResourceValue& res_val) {
                                           return (res_val.offset >= min_offset) && (res_val.offset < max_offset);
                                       });
                    res_vals.erase(end_iter, res_vals.end());

                    if (res_vals.empty())
                    {
                        tracked_values.erase(block_index);
                    }
                }
            }
        }
    }
}

void Dx12ExperimentalResourceValueTracker::PostProcessExecuteCommandLists(
    DxObjectInfo*                             command_queue_object_info,
    UINT                                      num_command_lists,
    HandlePointerDecoder<ID3D12CommandList*>* command_lists_decoder)
{
    auto command_queue_extra_info = GetExtraInfo<D3D12CommandQueueInfo>(command_queue_object_info);

    GFXRECON_ASSERT(command_queue_extra_info != nullptr);

    auto& pending_events = command_queue_extra_info->pending_events;

    ProcessExecuteCommandListArgs process_args{};

    for (UINT i = 0; i < num_command_lists; ++i)
    {
        auto command_list_id         = command_lists_decoder->GetPointer()[i];
        auto command_list_extra_info = GetExtraInfo<D3D12CommandListInfo>(get_object_info_func_(command_list_id));
        GFXRECON_ASSERT(command_list_extra_info != nullptr);

        process_args.resource_copies.insert(process_args.resource_copies.end(),
                                            command_list_extra_info->resource_copies.begin(),
                                            command_list_extra_info->resource_copies.end());

        auto tracker_command_list_info = tracker_command_list_infos_[command_list_id];

        for (const auto& non_dxr_resource_pair : tracker_command_list_info.non_dxr_resources_)
        {
            auto& args_vec = process_args.non_dxr_resources[non_dxr_resource_pair.first];
            args_vec.insert(args_vec.end(), non_dxr_resource_pair.second.begin(), non_dxr_resource_pair.second.end());
        }
    }

    // Run (or queue) resource value mapping process.
    if (pending_events.empty())
    {
        ProcessExecuteCommandList(std::move(process_args));
    }
    else
    {
        command_queue_extra_info->pending_events.push_back(
            CreateProcessExecuteCommandListSyncEvent(std::move(process_args)));
    }
}

void Dx12ExperimentalResourceValueTracker::PostProcessFillMemoryCommand(uint64_t       resource_id,
                                                                        uint64_t       offset,
                                                                        uint64_t       size,
                                                                        const uint8_t* data)
{
    TrackedFillCommandInfo tracked_fill_command;
    tracked_fill_command.fill_command_block_index = get_current_block_index_func_();
    tracked_fill_command.original_offset          = offset;
    tracked_fill_command.offset                   = offset;
    tracked_fill_command.size                     = size;

    Dx12ResourceValueTracker::PostProcessFillMemoryCommand(resource_id, offset, size, data);

    if (resolve_unassociated_values_)
    {
        auto resource_object_info = get_object_info_func_(resource_id);
        auto resource             = static_cast<ID3D12Resource*>(resource_object_info->object);
        if (resource->GetDesc().Dimension != D3D12_RESOURCE_DIMENSION_BUFFER)
        {
            return;
        }

        GFXRECON_ASSERT((offset % kMinDataAlignment) == 0);
        FindResourceValuesThreaded(tracked_fill_command, data, size);
    }

    UpdateFillCommandState(resource_id, tracked_fill_command);
}

void Dx12ExperimentalResourceValueTracker::PostProcessInitSubresourceCommand(
    ID3D12Resource* resource, const format::InitSubresourceCommandHeader& command_header, const uint8_t* data)
{
    GFXRECON_ASSERT(resource != nullptr);

    // Only support buffer resources.
    if (resource->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER)
    {
        // Buffer resources only have subresource 0.
        GFXRECON_ASSERT(command_header.subresource == 0);

        TrackedFillCommandInfo tracked_fill_command;
        tracked_fill_command.fill_command_block_index = get_current_block_index_func_();
        tracked_fill_command.original_offset          = 0;
        tracked_fill_command.offset                   = 0;
        tracked_fill_command.size                     = command_header.data_size;
        tracked_fill_command.init_subresource_data =
            std::make_shared<std::vector<uint8_t>>(std::vector<uint8_t>(data, data + command_header.data_size));

        if (resolve_unassociated_values_)
        {
            FindResourceValuesThreaded(tracked_fill_command, data, command_header.data_size);
        }

        UpdateFillCommandState(command_header.resource_id, tracked_fill_command);
    }
}

void Dx12ExperimentalResourceValueTracker::ProcessExecuteCommandList(ProcessExecuteCommandListArgs args)
{
    // Process non-DXR resource data ranges.
    for (const auto& non_dxr_resources_pair : args.non_dxr_resources)
    {
        auto resource_id = non_dxr_resources_pair.first;
        for (const auto& non_dxr_range : non_dxr_resources_pair.second)
        {
            AddNonDxrFillCommandBlocks(resource_id, non_dxr_range.first, non_dxr_range.second);
        }
    }

    Dx12ResourceValueTracker::ProcessExecuteCommandList(std::move(args));
}

bool MatchShaderIdentifier(const std::set<graphics::Dx12ShaderIdentifier>& shader_id_set, const uint8_t* data)
{
    for (const auto& shader_id : shader_id_set)
    {
        bool match = true;
        for (uint64_t i = 0; (i < D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES) && match; ++i)
        {
            match = match && (shader_id.data()[i] == data[i]);
        }
        if (match)
        {
            return true;
        }
    }
    return false;
}

void Dx12ExperimentalResourceValueTracker::FindResourceValues(
    const uint8_t*                                               data,
    uint64_t                                                     data_size,
    const std::set<graphics::Dx12ShaderIdentifier>*              shader_ids,
    const graphics::Dx12GpuVaMap*                                gpu_va_map,
    const decode::Dx12DescriptorMap*                             gpu_descriptor_map,
    std::vector<std::pair<uint64_t, format::ResourceValueType>>* found_resource_values) const
{
    found_resource_values->clear();

    const uint64_t kDescSize = sizeof(D3D12_GPU_DESCRIPTOR_HANDLE::ptr);
    const uint64_t kAddrSize = sizeof(uint64_t);
    const uint64_t kIdSize   = D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES;

    // These values were found through testing. They are useful for reducing computation time and the number of false
    // positives (data incorrectly identified as a resource value).
    const uint64_t kMinGpuVaAlignment = 16;

    for (uint64_t i = 0; (i + kMinDataAlignment) <= data_size; i += kMinDataAlignment)
    {
        // First check for a shader id match.
        if ((shader_ids != nullptr) && ((i + kIdSize) <= data_size))
        {
            if (MatchShaderIdentifier(*shader_ids, data + i))
            {
                found_resource_values->emplace_back(i, ResourceValueType::kShaderIdentifier);
                i += kIdSize - kMinDataAlignment;
                continue;
            }
        }

        // Next check for GPU descriptor match.
        if ((gpu_descriptor_map != nullptr) && ((i + kDescSize) <= data_size))
        {
            D3D12_GPU_DESCRIPTOR_HANDLE old_descriptor;
            util::platform::MemoryCopy(&old_descriptor.ptr, kDescSize, data + i, kDescSize);
            if ((old_descriptor.ptr >= min_gpu_descriptor_) && (old_descriptor.ptr < max_gpu_descriptor_) &&
                (old_descriptor.ptr % min_gpu_descriptor_alignment_ == 0))
            {
                bool found_descriptor = false;
                gpu_descriptor_map->GetGpuAddress(old_descriptor, &found_descriptor);
                if (found_descriptor)
                {
                    found_resource_values->emplace_back(i, ResourceValueType::kGpuDescriptorHandle);
                    i += kDescSize - kMinDataAlignment;
                    continue;
                }
            }
        }

        // Finally check for GPU VA match.
        if ((gpu_va_map != nullptr) && ((i + kAddrSize) <= data_size))
        {

            uint64_t old_address;
            util::platform::MemoryCopy(&old_address, kAddrSize, data + i, kAddrSize);
            if ((old_address >= min_gpu_va_) && (old_address < max_gpu_va_) && (old_address % kMinGpuVaAlignment == 0))
            {
                bool found_address = false;
                gpu_va_map->Map(old_address, nullptr, &found_address);
                if (found_address)
                {
                    found_resource_values->emplace_back(i, ResourceValueType::kGpuVirtualAddress);
                    i += kAddrSize - kMinDataAlignment;
                    continue;
                }
            }
        }
    }
}

void Dx12ExperimentalResourceValueTracker::FindResourceValuesThreaded(
    const TrackedFillCommandInfo& tracked_fill_command, const uint8_t* data, uint64_t data_size)
{
    const uint64_t kThreadCount = 8;

    if (find_resource_values_thread_datas_.size() < kThreadCount)
    {
        find_resource_values_thread_datas_.resize(kThreadCount);
    }

    const uint64_t kMinPerThreadSize = 512;
    uint64_t       per_thread_size   = util::platform::AlignValue<D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES>(
        std::max(data_size / kThreadCount, kMinPerThreadSize));
    uint64_t next_thread_offset = 0;
    for (auto& thread_data : find_resource_values_thread_datas_)
    {
        thread_data.data_offset = next_thread_offset;
        thread_data.data_size   = 0;
        if (data_size > next_thread_offset)
        {
            thread_data.data_size = std::min(per_thread_size, data_size - next_thread_offset);
        }
        next_thread_offset += thread_data.data_size;

        if (thread_data.data_size > 0)
        {
            thread_data.thread = std::thread(&Dx12ExperimentalResourceValueTracker::FindResourceValues,
                                             this,
                                             data + thread_data.data_offset,
                                             thread_data.data_size,
                                             &unique_unassociated_shader_ids_,
                                             &active_unassociated_gpu_va_map_,
                                             &active_unassociated_gpu_descriptor_map_,
                                             &thread_data.found_resource_values);
        }
    }

    for (auto& thread_data : find_resource_values_thread_datas_)
    {
        if (thread_data.data_size > 0)
        {
            thread_data.thread.join();
            for (const auto& found_resource_value : thread_data.found_resource_values)
            {
                AddBlockResourceValue(tracked_fill_command.fill_command_block_index,
                                      tracked_fill_command.original_offset + thread_data.data_offset +
                                          found_resource_value.first,
                                      found_resource_value.second);
            }
        }
    }
}

void Dx12ExperimentalResourceValueTracker::GetUnassociatedResourceValues(
    Dx12UnassociatedResourceValueMap& unassociated_values)
{
    if (track_unassociated_values_)
    {
        unassociated_values = std::move(unassociated_resource_values_);
        unassociated_resource_values_.clear();
    }
}

void Dx12ExperimentalResourceValueTracker::SetUnassociatedResourceValues(
    Dx12FillCommandResourceValueMap&& tracked_values, decode::Dx12UnassociatedResourceValueMap&& unassociated_values)
{
    GFXRECON_ASSERT(unassociated_resource_values_.empty());

    track_unassociated_values_   = false;
    resolve_unassociated_values_ = true;

    tracked_resource_values_      = std::move(tracked_values);
    unassociated_resource_values_ = std::move(unassociated_values);

    for (const auto& unassociated_resource_values_map : unassociated_resource_values_)
    {
        for (const auto& unassociated_resource_value_groups : unassociated_resource_values_map.second)
        {
            for (const auto& unassociated_resource_value : unassociated_resource_value_groups.values)
            {
                if (unassociated_resource_value.type == ResourceValueType::kShaderIdentifier)
                {
                    unique_unassociated_shader_ids_.insert(unassociated_resource_value.shader_id);
                }
                else if (unassociated_resource_value.type == ResourceValueType::kGpuVirtualAddress)
                {
                    if (unassociated_resource_value.resource_id != format::kNullHandleId)
                    {
                        all_unassociated_gpu_va_map_.insert(unassociated_resource_value.resource_id);
                    }
                }
                else if (unassociated_resource_value.type == ResourceValueType::kGpuDescriptorHandle)
                {
                    // TODO: Add heap info to Dx12UnassociatedResourceValue and fill in
                    // all_unassociated_gpu_descriptor_map_ here, then use that to limit GPU descriptor search.
                }
            }
        }
    }
}

void Dx12ExperimentalResourceValueTracker::AddShaderRecordData(format::HandleId                 resource_id,
                                                               uint64_t                         offset,
                                                               uint64_t                         shader_record_size,
                                                               const uint8_t*                   shader_record_data,
                                                               const graphics::Dx12GpuVaMap&    gpu_va_map,
                                                               const decode::Dx12DescriptorMap& descriptor_map)
{
    if (track_unassociated_values_ || resolve_unassociated_values_)
    {
        temp_found_shader_record_values_.clear();
        FindResourceValues(shader_record_data,
                           shader_record_size,
                           nullptr,
                           &gpu_va_map,
                           &descriptor_map,
                           &temp_found_shader_record_values_);
        for (const auto& found_resource_value : temp_found_shader_record_values_)
        {
            AddTrackedResourceValue(resource_id,
                                    found_resource_value.second,
                                    found_resource_value.first + offset,
                                    shader_record_data + found_resource_value.first,
                                    gpu_va_map);
        }
    }
}

void Dx12ExperimentalResourceValueTracker::AddNonDxrFillCommandBlocks(format::HandleId resource_id,
                                                                      uint64_t         resource_min_offset,
                                                                      uint64_t         resource_max_offset)
{
    auto& resource_fill_commands = tracked_fill_commands_[resource_id];

    auto iter = resource_fill_commands.begin();
    while (iter != resource_fill_commands.end())
    {
        auto next_iter = iter;
        ++next_iter;

        // If the incoming non DXR data region overlaps with tracked fill commands, compute the offsets in the original
        // fill command that the non DXR data came from and save to non_dxr_fill_command_data_.
        uint64_t fill_min_offset = iter->second.offset;
        uint64_t fill_max_offset = fill_min_offset + iter->second.size;
        bool     overlap         = (fill_min_offset < resource_max_offset) && (fill_max_offset > resource_min_offset);
        if (overlap)
        {
            uint64_t offset_min = std::max(resource_min_offset, fill_min_offset);
            uint64_t offset_max = std::min(resource_max_offset, fill_max_offset);

            uint64_t original_min = iter->second.original_offset + offset_min - iter->second.offset;
            uint64_t original_max = iter->second.original_offset + offset_max - iter->second.offset;

            auto& non_dxr_ranges         = non_dxr_fill_command_data_[iter->second.fill_command_block_index];
            non_dxr_ranges[original_min] = original_max;
        }

        if (resource_fill_commands.empty())
        {
            tracked_fill_commands_.erase(resource_id);
        }

        iter = next_iter;
    }
}

void Dx12ExperimentalResourceValueTracker::PostProcessCopyTextureRegion(
    DxObjectInfo*                                              command_list_object_info,
    StructPointerDecoder<Decoded_D3D12_TEXTURE_COPY_LOCATION>* dst_decoder,
    UINT                                                       dst_x,
    UINT                                                       dst_y,
    UINT                                                       dst_z,
    StructPointerDecoder<Decoded_D3D12_TEXTURE_COPY_LOCATION>* src_decoder,
    StructPointerDecoder<Decoded_D3D12_BOX>*                   src_box_decoder)
{
    if (resolve_unassociated_values_)
    {
        auto dst_copy_location = dst_decoder->GetPointer();
        auto src_copy_location = src_decoder->GetPointer();
        if ((dst_copy_location->Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX) &&
            (src_copy_location->Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT))
        {
            auto resource = dst_copy_location->pResource;
            if (resource != format::kNullHandleId)
            {
                auto        device           = graphics::dx12::GetDeviceComPtrFromChild<ID3D12Device>(resource);
                const auto& placed_footprint = src_copy_location->PlacedFootprint;
                uint64_t    copy_size        = 0;
                device->GetCopyableFootprints(&resource->GetDesc(),
                                              dst_copy_location->SubresourceIndex,
                                              1,
                                              placed_footprint.Offset,
                                              nullptr,
                                              nullptr,
                                              nullptr,
                                              &copy_size);

                auto  resource_id               = src_decoder->GetMetaStructPointer()->pResource;
                auto& tracker_command_list_info = tracker_command_list_infos_[command_list_object_info->capture_id];
                tracker_command_list_info.non_dxr_resources_[resource_id].push_back(
                    { placed_footprint.Offset, placed_footprint.Offset + copy_size });
            }
        }
    }
}

void Dx12ExperimentalResourceValueTracker::PostProcessIASetIndexBuffer(
    DxObjectInfo*                                          command_list_object_info,
    StructPointerDecoder<Decoded_D3D12_INDEX_BUFFER_VIEW>* views_decoder,
    const graphics::Dx12GpuVaMap&                          reverse_gpu_va_map)
{
    if (resolve_unassociated_values_)
    {
        auto index_buffer_view = views_decoder->GetPointer();
        if (index_buffer_view != nullptr)
        {
            auto resource_id = format::kNullHandleId;
            reverse_gpu_va_map.Map(index_buffer_view->BufferLocation, &resource_id);
            if (resource_id != format::kNullHandleId)
            {
                auto resource_object_info = get_object_info_func_(resource_id);
                auto resource             = static_cast<ID3D12Resource*>(resource_object_info->object);
                auto buffer_offset        = index_buffer_view->BufferLocation - resource->GetGPUVirtualAddress();

                auto& tracker_command_list_info = tracker_command_list_infos_[command_list_object_info->capture_id];
                tracker_command_list_info.non_dxr_resources_[resource_id].push_back(
                    { buffer_offset, buffer_offset + index_buffer_view->SizeInBytes });
            }
        }
    }
}

void Dx12ExperimentalResourceValueTracker::PostProcessIASetVertexBuffers(
    DxObjectInfo*                                           command_list_object_info,
    UINT                                                    start_slot,
    UINT                                                    num_views,
    StructPointerDecoder<Decoded_D3D12_VERTEX_BUFFER_VIEW>* views_decoder,
    const graphics::Dx12GpuVaMap&                           reverse_gpu_va_map)
{
    if (resolve_unassociated_values_)
    {
        auto vertex_buffer_view = views_decoder->GetPointer();
        if (vertex_buffer_view != nullptr)
        {
            auto resource_id = format::kNullHandleId;
            reverse_gpu_va_map.Map(vertex_buffer_view->BufferLocation, &resource_id);
            if (resource_id != format::kNullHandleId)
            {
                auto resource_object_info = get_object_info_func_(resource_id);
                auto resource             = static_cast<ID3D12Resource*>(resource_object_info->object);
                auto buffer_offset        = vertex_buffer_view->BufferLocation - resource->GetGPUVirtualAddress();

                auto& tracker_command_list_info = tracker_command_list_infos_[command_list_object_info->capture_id];
                tracker_command_list_info.non_dxr_resources_[resource_id].push_back(
                    { buffer_offset, buffer_offset + vertex_buffer_view->SizeInBytes });
            }
        }
    }
}

void Dx12ExperimentalResourceValueTracker::PostProcessCommandListReset(DxObjectInfo* command_list_object_info)
{
    tracker_command_list_infos_[command_list_object_info->capture_id].Reset();
}

void Dx12ExperimentalResourceValueTracker::AddResourceGpuVa(format::HandleId          resource_id,
                                                            D3D12_GPU_VIRTUAL_ADDRESS replay_address,
                                                            UINT64                    width,
                                                            D3D12_GPU_VIRTUAL_ADDRESS capture_address)
{
    if (track_unassociated_values_)
    {
        min_gpu_va_ = std::min(min_gpu_va_, capture_address);
        max_gpu_va_ = std::max(max_gpu_va_, capture_address + width);
    }
    else if (all_unassociated_gpu_va_map_.count(resource_id) > 0)
    {
        active_unassociated_gpu_va_map_.Add(resource_id, capture_address, width, replay_address);
        min_gpu_va_ = std::min(min_gpu_va_, capture_address);
        max_gpu_va_ = std::max(max_gpu_va_, capture_address + width);
    }
}

void Dx12ExperimentalResourceValueTracker::RemoveResourceGpuVa(format::HandleId resource_id, uint64_t capture_address)
{
    active_unassociated_gpu_va_map_.Remove(resource_id, capture_address);
}

void Dx12ExperimentalResourceValueTracker::AddGpuDescriptorHeap(
    const D3D12_GPU_DESCRIPTOR_HANDLE&     capture_gpu_start,
    const D3D12_GPU_DESCRIPTOR_HANDLE&     replay_gpu_start,
    D3D12_DESCRIPTOR_HEAP_TYPE             heap_info_descriptor_type,
    uint32_t                               heap_info_descriptor_count,
    std::shared_ptr<DescriptorIncrements>& heap_info_capture_increments,
    std::shared_ptr<DescriptorIncrements>& heap_info_replay_increments)
{
    min_gpu_descriptor_ = std::min(min_gpu_descriptor_, capture_gpu_start.ptr);
    max_gpu_descriptor_ =
        std::max(max_gpu_descriptor_,
                 capture_gpu_start.ptr + static_cast<uint64_t>(heap_info_descriptor_count) *
                                             (*heap_info_capture_increments)[heap_info_descriptor_type]);

    if (resolve_unassociated_values_)
    {
        active_unassociated_gpu_descriptor_map_.AddGpuDescriptorHeap(capture_gpu_start,
                                                                     replay_gpu_start,
                                                                     heap_info_descriptor_type,
                                                                     heap_info_descriptor_count,
                                                                     heap_info_capture_increments,
                                                                     heap_info_replay_increments);
    }

    for (auto increment : *heap_info_capture_increments)
    {
        if (increment > 0)
        {
            min_gpu_descriptor_alignment_ = std::min(min_gpu_descriptor_alignment_, static_cast<uint64_t>(increment));
        }
    }
}

void Dx12ExperimentalResourceValueTracker::RemoveGpuDescriptorHeap(uint64_t capture_gpu_start)
{
    active_unassociated_gpu_descriptor_map_.RemoveGpuDescriptorHeap(capture_gpu_start);
}

GFXRECON_END_NAMESPACE(decode)
GFXRECON_END_NAMESPACE(gfxrecon)