upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/d3d12_com.cpp
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 22:35:34 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 22:35:34 -0500
commit6ed716a99a7416f1e8a60c2e38e128876ab752ec (patch)
tree3c35526aa8b96594252c82c278ab19b9aa3a98ba /runtime/shims/d3d12_com.cpp
parent028a414fade7058a96e5933d1325f374a0026588 (diff)
parentbfef489cb6307fa4e1dc6ed2c40bfc0ce120d066 (diff)
Merge main into RT-QUEUE-SIGNAL (#430)
Everything below this rung (#414, #416, #427) and the rung's own routing are in main already, through #984 and #939, in main's form; what is left of #430 is its test of queue slot 17, ported onto main's layout detection. Conflicts, all resolved to main's form: - runtime/shims/d3d12_xs_device.cpp: main's queue slot 16/17 rule (a fence there is the newer layout's Signal/Wait, for any caller) replaces the rung's caller-gated rule; main's PresentX routing (slot 30, or 32 once the newer layout is detected, LEONIDA_XS_PRESENT_X_SLOT) and lazily built presenter replace the fixed slot 32 of #414; main's list proxy already translates the CPU handles of console list slots 50 to 54 (#416) and drops unordered access from a depth-stencil texture at slot 76 (#427). - runtime/shims/d3d12_xs_device.h, runtime/shims/xbox_present.cpp, runtime/shims/xbox_present.h, runtime/src/frame_pacer.h: main's shared FrameTokenSource (Logan's piece of #414, as #984 carried it). - runtime/shims/d3d12_xs_desc_clean.h, runtime/test/device_proxy_test.cpp: main's without_depth_stencil_uav and its slot 25/76 test (#427). - runtime/test/xs_proxy_mock_test.cpp: main's file, which already has check_list_cpu_handles (#416's cases and more); the rung's slot 16/17 case is ported to main's form at the end of check_xbox_queue_slots: slot 16 and 17 with a fence reach PC Signal and Wait with the real fence, not the PC getters, and the fence proxy's vtable pointer is unchanged. The rung's host-caller and no-fence expectations are dropped: under main's rule a fence at 16 proves the newer layout, after which those calls answer S_OK. Auto-merged, then set to main's content: - runtime/test/queue_proxy_test.cpp: #414's call of queue slot 32 as an overridden slot; on main slot 32 is routed only on the newer layout and the sweep of the console tail already calls it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/shims/d3d12_com.cpp')
-rw-r--r--runtime/shims/d3d12_com.cpp689
1 files changed, 631 insertions, 58 deletions
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index cf02df519..883cce32a 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -1,3 +1,4 @@
1#include <cstdlib>
1#include "d3d12_com.h" 2#include "d3d12_com.h"
2 3
3#include "d3d12_stubs.h" // generated 4#include "d3d12_stubs.h" // generated
@@ -6,20 +7,27 @@
6#include "d3d12_trace.h" 7#include "d3d12_trace.h"
7#include "d3d12_xs_device.h" 8#include "d3d12_xs_device.h"
8#include "../src/gfx10_descriptors.h" 9#include "../src/gfx10_descriptors.h"
10#include "../src/title_va_alias.h"
11#include "../src/fsdraw_probe.h" // LOCAL DIAGNOSTIC
12#include "../src/local_diagnostics.h"
9 13
10#include <algorithm> 14#include <algorithm>
11#include <array> 15#include <array>
12#include <atomic> 16#include <atomic>
13#include <bit> 17#include <bit>
18#include <chrono>
14#include <condition_variable> 19#include <condition_variable>
15#include <functional> 20#include <functional>
21#include <map>
16#include <memory> 22#include <memory>
17#include <optional> 23#include <optional>
18#include <cstdio> 24#include <cstdio>
19#include <cstring> 25#include <cstring>
20#include <mutex> 26#include <mutex>
21#include <set> 27#include <set>
28#include <source_location>
22#include <string> 29#include <string>
30#include <string_view>
23#include <thread> 31#include <thread>
24#include <utility> 32#include <utility>
25#include <vector> 33#include <vector>
@@ -198,8 +206,19 @@ public:
198 } 206 }
199 207
200 const leonida::CommandList& commands() const { return list_; } 208 const leonida::CommandList& commands() const { return list_; }
209 // The descriptor tables this recording binds (console VAs), for the scan before a submission.
210 const std::vector<std::pair<std::uint64_t, std::uint32_t>>& tables() const { return tables_; }
201 // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). 211 // The pipeline states and root signatures the recording names (it holds a reference to each until Reset).
202 const std::vector<IUnknown*>& pinned() const { return held_; } 212 const std::vector<IUnknown*>& pinned() const { return held_; }
213 bool needs_all_sampled_views() const {
214 if (directly_indexed_) return true;
215 for (const auto& command : list_.commands()) {
216 if (std::holds_alternative<leonida::ExecuteIndirect>(command)) return true;
217 if (tables_.empty() && (std::holds_alternative<leonida::Draw>(command) ||
218 std::holds_alternative<leonida::Dispatch>(command))) return true;
219 }
220 return false;
221 }
203 UINT front_stencil_ref() const { return front_stencil_ref_; } 222 UINT front_stencil_ref() const { return front_stencil_ref_; }
204 UINT back_stencil_ref() const { return back_stencil_ref_; } 223 UINT back_stencil_ref() const { return back_stencil_ref_; }
205 D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base() const { return cbv_srv_uav_base_; } 224 D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base() const { return cbv_srv_uav_base_; }
@@ -234,6 +253,8 @@ public:
234 record_into(command_allocator); 253 record_into(command_allocator);
235 invalid_ = false; 254 invalid_ = false;
236 calls_.clear(); 255 calls_.clear();
256 tables_.clear();
257 directly_indexed_ = false;
237 release_held(); // what the old recording used: it was replayed at ExecuteCommandLists 258 release_held(); // what the old recording used: it was replayed at ExecuteCommandLists
238 reset_state(state); // Reset returns every list state to its default 259 reset_state(state); // Reset returns every list state to its default
239 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it 260 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it
@@ -411,12 +432,20 @@ public:
411 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); 432 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false);
412 if (!count) { 433 if (!count) {
413 viewport_ = {}; 434 viewport_ = {};
435 viewports_.fill({});
436 viewport_count_ = 0;
437 draw_viewports_stale_ = true;
414 return; 438 return;
415 } 439 }
416 if (!viewports || count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) return check(false); 440 if (!viewports || count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) return check(false);
417 if (count > 1) stub("ID3D12GraphicsCommandList::RSSetViewports (more than one viewport; the first is used)"); 441 viewports_.fill({});
418 const D3D12_VIEWPORT& v = viewports[0]; 442 for (UINT i = 0; i < count; ++i) {
419 viewport_ = {v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth}; 443 const D3D12_VIEWPORT& v = viewports[i];
444 viewports_[i] = {v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth};
445 }
446 viewport_count_ = count;
447 viewport_ = viewports_[0];
448 draw_viewports_stale_ = true;
420 } 449 }
421 450
422 void STDMETHODCALLTYPE RSSetScissorRects(UINT count, const D3D12_RECT* rects) override { 451 void STDMETHODCALLTYPE RSSetScissorRects(UINT count, const D3D12_RECT* rects) override {
@@ -425,11 +454,25 @@ public:
425 // With no scissor bound, the rasterizer clips every fragment, as on native D3D12. 454 // With no scissor bound, the rasterizer clips every fragment, as on native D3D12.
426 if (!count) { 455 if (!count) {
427 scissor_ = {}; 456 scissor_ = {};
457 scissors_.fill({});
458 scissor_count_ = 0;
459 draw_viewports_stale_ = true;
428 return; 460 return;
429 } 461 }
430 if (!rects) return; 462 if (!rects) return;
431 if (count > 1) stub("ID3D12GraphicsCommandList::RSSetScissorRects (more than one rectangle; the first is used)"); 463 // WARP still closes a list after RSSetScissorRects(17) (d3d12_close_parity), so the call is not an error:
432 scissor_ = {rects[0].left, rects[0].top, rects[0].right, rects[0].bottom}; 464 // the rectangles past the 16 a pipeline can have are dropped.
465 if (count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) {
466 stub("ID3D12GraphicsCommandList::RSSetScissorRects(more than 16 rectangles; the first 16 are used)");
467 count = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
468 }
469 scissors_.fill({});
470 for (UINT i = 0; i < count; ++i) {
471 scissors_[i] = {rects[i].left, rects[i].top, rects[i].right, rects[i].bottom};
472 }
473 scissor_count_ = count;
474 scissor_ = scissors_[0];
475 draw_viewports_stale_ = true;
433 } 476 }
434 477
435 // D3D12 reads render-target and depth descriptors here, so their views are copied now. 478 // D3D12 reads render-target and depth descriptors here, so their views are copied now.
@@ -486,10 +529,31 @@ public:
486 d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh"); 529 d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh");
487 if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false); 530 if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false);
488 if (!graphics_pipeline_ || !graphics_.layout) return check(false); 531 if (!graphics_pipeline_ || !graphics_.layout) return check(false);
489 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized 532 // A mesh shader reads the root arguments from s16 through a 16-dword window (RootArgumentLayout::mesh_ok).
490 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, 533 if (!graphics_.layout->mesh_ok) {
534 stub("DispatchMesh(root signature larger than a mesh shader's root window)");
535 return check(false);
536 }
537 // The directly indexed heaps follow the arguments (graphics_user_data). The window shows a mesh shader push
538 // dwords 8..23 only (s16..s31), so a signature that fills it leaves a heap where the mesh stage cannot read.
539 {
540 constexpr std::uint32_t window_end = rt::rootsig::stage_base(rt::rootsig::Stage::Pixel) +
541 rt::rootsig::kMaxUserSgprs -
542 rt::rootsig::stage_base(rt::rootsig::Stage::Mesh);
543 const auto flags = graphics_.layout->flags;
544 const bool resource = flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED;
545 const bool sampler = flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
546 const std::uint32_t end = graphics_.layout->graphics_arguments_end;
547 if (resource && end >= window_end)
548 note_once("mesh direct heaps: no SGPR left in the mesh window (s16..s31) for the resource heap");
549 if (sampler && end + (resource ? 1u : 0u) >= window_end)
550 note_once("mesh direct heaps: no SGPR left in the mesh window (s16..s31) for the sampler heap");
551 }
552 if (!any_nonempty_viewport()) return; // as record_draw: nothing is rasterized
553 leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, {}, 0, viewport_,
491 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; 554 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0};
492 draw.mesh = true; 555 draw.mesh = true;
556 draw.viewports = draw_viewports();
493 check(list_.draw(std::move(draw))); 557 check(list_.draw(std::move(draw)));
494 } 558 }
495 559
@@ -499,19 +563,30 @@ public:
499 for (UINT i = 0; i < count; ++i) { 563 for (UINT i = 0; i < count; ++i) {
500 const auto& b = barriers[i]; 564 const auto& b = barriers[i];
501 switch (b.Type) { 565 switch (b.Type) {
502 case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION: 566 case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION: {
503 check(list_.transition({resource_id(b.Transition.pResource), b.Transition.Subresource, 567 const auto& t = b.Transition;
504 static_cast<std::uint32_t>(b.Transition.StateBefore), 568 const auto logical = resource_id(t.pResource);
505 static_cast<std::uint32_t>(b.Transition.StateAfter)}, 569 const bool was_storage = (t.StateBefore & D3D12_RESOURCE_STATE_UNORDERED_ACCESS) != 0;
506 static_cast<std::uint32_t>(b.Flags))); 570 const bool storage = (t.StateAfter & D3D12_RESOURCE_STATE_UNORDERED_ACCESS) != 0;
571 const auto pair = (was_storage || storage) ? xbox_depth_storage(t.pResource) : XboxDepthStorage{};
572 auto before = t.StateBefore;
573 if (pair.colour && was_storage != storage && !(b.Flags & D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY)) {
574 check(copy_depth_storage(logical, pair, storage, {t.Subresource}));
575 before = D3D12_RESOURCE_STATE_COPY_DEST;
576 }
577 check(list_.transition({pair.colour && storage ? pair.colour : logical, t.Subresource,
578 u(before), u(t.StateAfter)}, u(b.Flags)));
507 break; 579 break;
580 }
508 case D3D12_RESOURCE_BARRIER_TYPE_ALIASING: 581 case D3D12_RESOURCE_BARRIER_TYPE_ALIASING:
509 check(!b.Flags && list_.aliasing_barrier({resource_id(b.Aliasing.pResourceBefore), 582 check(!b.Flags && list_.aliasing_barrier({resource_id(b.Aliasing.pResourceBefore),
510 resource_id(b.Aliasing.pResourceAfter)})); 583 resource_id(b.Aliasing.pResourceAfter)}));
511 break; 584 break;
512 case D3D12_RESOURCE_BARRIER_TYPE_UAV: 585 case D3D12_RESOURCE_BARRIER_TYPE_UAV: {
513 check(!b.Flags && list_.uav_barrier({resource_id(b.UAV.pResource)})); 586 const auto pair = xbox_depth_storage(b.UAV.pResource);
587 check(!b.Flags && list_.uav_barrier({pair.colour ? pair.colour : resource_id(b.UAV.pResource)}));
514 break; 588 break;
589 }
515 default: 590 default:
516 check(false); 591 check(false);
517 } 592 }
@@ -526,29 +601,61 @@ public:
526 switch (group[g].Type) { 601 switch (group[g].Type) {
527 case D3D12_BARRIER_TYPE_GLOBAL: { 602 case D3D12_BARRIER_TYPE_GLOBAL: {
528 const auto& b = group[g].pGlobalBarriers[i]; 603 const auto& b = group[g].pGlobalBarriers[i];
529 check(list_.barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), 604 if (!list_.barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore),
530 u(b.AccessAfter)})); 605 u(b.AccessAfter)}) &&
606 reject())
607 std::fprintf(stderr, "[rt] d3d12: global barrier sync 0x%x->0x%x access 0x%x->0x%x\n",
608 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter));
531 break; 609 break;
532 } 610 }
533 case D3D12_BARRIER_TYPE_BUFFER: { 611 case D3D12_BARRIER_TYPE_BUFFER: {
534 const auto& b = group[g].pBufferBarriers[i]; 612 const auto& b = group[g].pBufferBarriers[i];
535 check(list_.barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), 613 if (!list_.barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore),
536 u(b.AccessAfter), resource_id(b.pResource)})); 614 u(b.AccessAfter), resource_id(b.pResource)}) &&
615 reject()) {
616 std::fprintf(stderr, "[rt] d3d12: buffer barrier sync 0x%x->0x%x access 0x%x->0x%x offset "
617 "0x%llx size 0x%llx\n",
618 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter),
619 static_cast<unsigned long long>(b.Offset), static_cast<unsigned long long>(b.Size));
620 describe_barrier_resource(b.pResource);
621 }
537 break; 622 break;
538 } 623 }
539 case D3D12_BARRIER_TYPE_TEXTURE: { 624 case D3D12_BARRIER_TYPE_TEXTURE: {
540 const auto& b = group[g].pTextureBarriers[i]; 625 const auto& b = group[g].pTextureBarriers[i];
541 const auto& r = b.Subresources; 626 const auto& r = b.Subresources;
542 check(list_.barrier(leonida::TextureBarrier{ 627 leonida::TextureBarrier barrier{
543 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore), 628 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore),
544 u(b.LayoutAfter), resource_id(b.pResource), 629 u(b.LayoutAfter), resource_id(b.pResource),
545 {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, 630 {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane,
546 r.NumPlanes}, 631 r.NumPlanes}, u(b.Flags)};
547 u(b.Flags)})); 632 const bool was_storage = storage_access(b.LayoutBefore, b.AccessBefore);
633 const bool storage = storage_access(b.LayoutAfter, b.AccessAfter);
634 const auto pair = (was_storage || storage) ? xbox_depth_storage(b.pResource) : XboxDepthStorage{};
635 if (pair.colour) {
636 if (was_storage != storage && b.SyncAfter != D3D12_BARRIER_SYNC_SPLIT &&
637 b.LayoutBefore != D3D12_BARRIER_LAYOUT_UNDEFINED && !(b.Flags & D3D12_TEXTURE_BARRIER_FLAG_DISCARD)) {
638 check(copy_depth_storage(barrier.resource, pair, storage, barrier.range));
639 barrier.sync_before = leonida::d3d12_sync::copy;
640 barrier.access_before = leonida::d3d12_access::copy_dest;
641 barrier.layout_before = leonida::d3d12_layout::copy_dest;
642 }
643 if (storage) barrier.resource = pair.colour;
644 }
645 if (!list_.barrier(barrier) && reject()) {
646 std::fprintf(stderr,
647 "[rt] d3d12: texture barrier sync 0x%x->0x%x access 0x%x->0x%x layout %u->%u "
648 "mips %u+%u layers %u+%u planes %u+%u flags 0x%x\n",
649 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter),
650 u(b.LayoutBefore), u(b.LayoutAfter), r.IndexOrFirstMipLevel, r.NumMipLevels,
651 r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, r.NumPlanes, u(b.Flags));
652 describe_barrier_resource(b.pResource);
653 }
548 break; 654 break;
549 } 655 }
550 default: 656 default:
551 check(false); 657 if (reject())
658 std::fprintf(stderr, "[rt] d3d12: barrier group type %d\n", int(group[g].Type));
552 } 659 }
553 } 660 }
554 } 661 }
@@ -616,7 +723,24 @@ public:
616 if (!dst || !src) return check(false); 723 if (!dst || !src) return check(false);
617 leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}}; 724 leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}};
618 if (box) copy.box = {box->left, box->top, box->front, box->right, box->bottom, box->back}; 725 if (box) copy.box = {box->left, box->top, box->front, box->right, box->bottom, box->back};
619 check(list_.copy_texture(copy)); 726 if (!list_.copy_texture(copy) && reject()) {
727 for (const auto* l : {dst, src}) {
728 const char* side = l == dst ? "dst" : "src";
729 if (l->Type != D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) {
730 std::fprintf(stderr, "[rt] d3d12: %s type %d resource %p subresource %u\n", side, int(l->Type),
731 static_cast<void*>(l->pResource), l->SubresourceIndex);
732 continue;
733 }
734 const auto& f = l->PlacedFootprint;
735 std::fprintf(stderr, "[rt] d3d12: %s footprint resource %p offset 0x%llx format %d %ux%ux%u pitch %u\n",
736 side, static_cast<void*>(l->pResource), static_cast<unsigned long long>(f.Offset),
737 int(f.Footprint.Format), f.Footprint.Width, f.Footprint.Height, f.Footprint.Depth,
738 f.Footprint.RowPitch);
739 }
740 if (box)
741 std::fprintf(stderr, "[rt] d3d12: at %u,%u,%u box %u,%u,%u-%u,%u,%u\n", x, y, z, box->left, box->top,
742 box->front, box->right, box->bottom, box->back);
743 }
620 } 744 }
621 745
622 void STDMETHODCALLTYPE CopyResource(ID3D12Resource* dst, ID3D12Resource* src) override { 746 void STDMETHODCALLTYPE CopyResource(ID3D12Resource* dst, ID3D12Resource* src) override {
@@ -698,6 +822,18 @@ public:
698 d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); 822 d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView");
699 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); 823 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false);
700 if (!view.ptr || !color) return check(false); 824 if (!view.ptr || !color) return check(false);
825 // LOCAL DIAGNOSTIC: what the title clears, and with which colour
826 if (leonida::local_diagnostics()) {
827 static std::atomic<std::uint64_t> clears{0};
828 const std::uint64_t n = ++clears;
829 if (n <= 6 || n % 600 == 0) {
830 const auto& t = *reinterpret_cast<const leonida::TargetView*>(view.ptr);
831 std::fprintf(stderr, "[rt] present-probe: ClearRenderTargetView #%llu resource 0x%llx mip %u layers %u+%u "
832 "colour %.3f %.3f %.3f %.3f rects %u\n",
833 static_cast<unsigned long long>(n), static_cast<unsigned long long>(t.resource), t.mip,
834 t.first_layer, t.layer_count, color[0], color[1], color[2], color[3], count);
835 }
836 }
701 check(list_.clear_render_target(*reinterpret_cast<const leonida::TargetView*>(view.ptr), 837 check(list_.clear_render_target(*reinterpret_cast<const leonida::TargetView*>(view.ptr),
702 {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); 838 {color[0], color[1], color[2], color[3]}, to_rects(count, rects)));
703 } 839 }
@@ -835,9 +971,7 @@ public:
835 return check(false); 971 return check(false);
836 } 972 }
837 // The record size is checked for every call: D3D12 rejects a signature whose stride cannot hold a record 973 // The record size is checked for every call: D3D12 rejects a signature whose stride cannot hold a record
838 // even when no command runs. The argument span is what the signature can walk, max_command_count * stride: 974 // even when no command runs.
839 // the host refuses a range that ends past the buffer (`240` with stride `20` in a `256`-byte buffer), and
840 // it checks the offset itself when max_command_count is 0, where the required bytes are none.
841 const UINT64 record_size = 975 const UINT64 record_size =
842 kind == leonida::IndirectKind::draw ? sizeof(D3D12_DRAW_ARGUMENTS) 976 kind == leonida::IndirectKind::draw ? sizeof(D3D12_DRAW_ARGUMENTS)
843 : kind == leonida::IndirectKind::draw_indexed ? sizeof(D3D12_DRAW_INDEXED_ARGUMENTS) 977 : kind == leonida::IndirectKind::draw_indexed ? sizeof(D3D12_DRAW_INDEXED_ARGUMENTS)
@@ -845,9 +979,18 @@ public:
845 : kind == leonida::IndirectKind::dispatch_mesh ? sizeof(D3D12_DISPATCH_MESH_ARGUMENTS) 979 : kind == leonida::IndirectKind::dispatch_mesh ? sizeof(D3D12_DISPATCH_MESH_ARGUMENTS)
846 : 0; 980 : 0;
847 if (!record_size || stride < record_size || stride % 4 != 0) return check(false); 981 if (!record_size || stride < record_size || stride % 4 != 0) return check(false);
848 if (argument_buffer_offset > arg_desc.Width || 982 // The argument range is the bytes the commands read: (max_command_count - 1) * stride + record_size, and
849 UINT64(max_command_count) > (arg_desc.Width - argument_buffer_offset) / stride) 983 // nothing when max_command_count is 0. PC D3D12 runtimes do not agree here. Some bound max_command_count *
850 return check(false); 984 // stride and check the offset at a zero count; others (D3D12Core 10.0.26100.9818, WARP and NVIDIA alike)
985 // accept a last record that fits while its stride runs past the buffer, and any aligned offset at a zero
986 // count. The layer takes the wider rule: it is the one Vulkan's own indirect draws use, no byte outside the
987 // buffer is read, and refusing here drops the whole command list for a call a real runtime runs.
988 // d3d12_execute_indirect_validation_test lists the five cases the runtimes split on.
989 if (max_command_count) {
990 const UINT64 required = UINT64(max_command_count - 1) * stride + record_size;
991 if (argument_buffer_offset > arg_desc.Width || arg_desc.Width - argument_buffer_offset < required)
992 return check(false);
993 }
851 if (kind == leonida::IndirectKind::dispatch_mesh) { 994 if (kind == leonida::IndirectKind::dispatch_mesh) {
852 // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the 995 // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the
853 // first such call says so. The list stays valid. 996 // first such call says so. The list stays valid.
@@ -868,7 +1011,7 @@ public:
868 if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record 1011 if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record
869 if (!compute_pipeline_ || !compute_.layout) return check(false); 1012 if (!compute_pipeline_ || !compute_.layout) return check(false);
870 cmd.pipeline = compute_pipeline_; 1013 cmd.pipeline = compute_pipeline_;
871 cmd.user_data = compute_.data; 1014 cmd.user_data = compute_user_data();
872 } 1015 }
873 check(list_.execute_indirect(cmd)); 1016 check(list_.execute_indirect(cmd));
874 } 1017 }
@@ -978,9 +1121,47 @@ public:
978 check(list_.copy_acceleration_structure({dest, source, static_cast<std::uint32_t>(mode)})); 1121 check(list_.copy_acceleration_structure({dest, source, static_cast<std::uint32_t>(mode)}));
979 } 1122 }
980 1123
1124 bool xbox_label(const leonida::label::Write& op) { return list_.write_gpu_label(op); }
981 static GraphicsCommandList* from(IUnknown* object) { return Child::from<GraphicsCommandList>(object); } 1125 static GraphicsCommandList* from(IUnknown* object) { return Child::from<GraphicsCommandList>(object); }
982 1126
983private: 1127private:
1128 static bool storage_access(D3D12_BARRIER_LAYOUT layout, D3D12_BARRIER_ACCESS access) {
1129 return (access & D3D12_BARRIER_ACCESS_UNORDERED_ACCESS) ||
1130 layout == D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS ||
1131 layout == D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS ||
1132 layout == D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS;
1133 }
1134
1135 bool copy_depth_storage(leonida::ResourceId depth, XboxDepthStorage pair, bool to_storage,
1136 const leonida::BarrierSubresourceRange& r) {
1137 namespace access = leonida::d3d12_access;
1138 namespace sync = leonida::d3d12_sync;
1139 const auto from = to_storage ? depth : pair.colour, to = to_storage ? pair.colour : depth;
1140 // The two images can be in GENERAL for bindless use. Order prior depth writes, unordered writes and
1141 // readers of the destination even when Vulkan does not need a layout transition.
1142 if (!list_.barrier(leonida::GlobalBarrier{sync::all, sync::copy,
1143 access::depth_stencil_write | access::depth_stencil_read | access::unordered_access |
1144 access::shader_resource | access::copy_source | access::copy_dest,
1145 access::copy_source | access::copy_dest})) return false;
1146 if (!r.mip_count && r.index_or_first_mip == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES)
1147 return list_.copy_resource({to, from});
1148 const auto one = [&](UINT subresource) {
1149 leonida::CopyTexture copy{};
1150 copy.src.resource = from;
1151 copy.dst.resource = to;
1152 copy.src.subresource = copy.dst.subresource = subresource;
1153 return list_.copy_texture(copy);
1154 };
1155 if (!r.mip_count) return r.index_or_first_mip < pair.mips * pair.layers && one(r.index_or_first_mip);
1156 if (r.first_plane || r.plane_count != 1 || !r.layer_count ||
1157 r.first_layer >= pair.layers || r.layer_count > pair.layers - r.first_layer ||
1158 r.index_or_first_mip >= pair.mips || r.mip_count > pair.mips - r.index_or_first_mip) return false;
1159 for (UINT layer = r.first_layer; layer < r.first_layer + r.layer_count; ++layer)
1160 for (UINT mip = r.index_or_first_mip; mip < r.index_or_first_mip + r.mip_count; ++mip)
1161 if (!one(layer * pair.mips + mip)) return false;
1162 return true;
1163 }
1164
984 static bool valid_postbuild_info_type(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE type) { 1165 static bool valid_postbuild_info_type(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE type) {
985 switch (type) { 1166 switch (type) {
986 case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE: 1167 case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE:
@@ -1026,8 +1207,35 @@ private:
1026 return out; 1207 return out;
1027 } 1208 }
1028 1209
1029 void check(bool ok) { 1210 // Records an invalid call: Close then returns E_INVALIDARG and ExecuteCommandLists refuses the list. The first
1030 if (!ok) invalid_ = true; 1211 // rejection at each call site is logged with the method and line, so a failed Close names its cause; reject()
1212 // returns true for that first one, when a caller may print the arguments too.
1213 bool reject(std::source_location where = std::source_location::current()) {
1214 invalid_ = true;
1215 static std::array<std::atomic<bool>, 4096> seen{};
1216 const std::uint_least32_t line = where.line();
1217 if (line < seen.size() && seen[line].exchange(true, std::memory_order_relaxed)) return false;
1218 std::string_view method = where.function_name();
1219 if (const auto at = method.find("GraphicsCommandList::"); at != std::string_view::npos)
1220 method.remove_prefix(at);
1221 if (const auto paren = method.find('('); paren != std::string_view::npos) method = method.substr(0, paren);
1222 std::fprintf(stderr, "[rt] d3d12: %.*s rejected a call (d3d12_com.cpp:%u): the list's Close returns "
1223 "E_INVALIDARG and ExecuteCommandLists refuses it\n",
1224 int(method.size()), method.data(), unsigned(line));
1225 return true;
1226 }
1227 void check(bool ok, std::source_location where = std::source_location::current()) {
1228 if (!ok) reject(where);
1229 }
1230 static void describe_barrier_resource(ID3D12Resource* resource) {
1231 if (!resource) return void(std::fprintf(stderr, "[rt] d3d12: resource null\n"));
1232 const D3D12_RESOURCE_DESC desc = resource->GetDesc();
1233 std::fprintf(stderr,
1234 "[rt] d3d12: resource %p dimension %d format %d %llux%ux%u mips %u samples %u layout %d "
1235 "flags 0x%x\n",
1236 static_cast<void*>(resource), int(desc.Dimension), int(desc.Format),
1237 static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
1238 desc.SampleDesc.Count, int(desc.Layout), unsigned(desc.Flags));
1031 } 1239 }
1032 1240
1033 void stop_recording() { 1241 void stop_recording() {
@@ -1130,12 +1338,24 @@ private:
1130 if (g::is_image(words)) { 1338 if (g::is_image(words)) {
1131 g::Image image{}; 1339 g::Image image{};
1132 if (!g::decode(words, image)) return false; 1340 if (!g::decode(words, image)) return false;
1341 out.resource = uav_image_resource(resource, image.address);
1342 if (!out.resource) return false;
1133 const bool volume = image.type == g::ImageType::image_3d; 1343 const bool volume = image.type == g::ImageType::image_3d;
1344 const auto pair = xbox_depth_storage(resource);
1345 if (pair.colour) out.resource = pair.colour;
1346 if (g::partial_volume_uav(words, image)) {
1347 // Transfer clears operate on a whole 3D mip, not a storage image view. Refuse instead of
1348 // overwriting slices outside the UAV; a sliced clear needs a separate replay path.
1349 stub("ClearUnorderedAccessView of a partial 3D mip");
1350 return false;
1351 }
1134 out.buffer = false; 1352 out.buffer = false;
1135 out.format = std::uint32_t(descriptor_format(image.format, image.swizzle)); 1353 out.format = std::uint32_t(descriptor_format(image.format, image.swizzle));
1136 out.mip = image.first_mip; 1354 out.mip = image.first_mip;
1137 out.first_layer = volume ? 0 : image.first_layer; // a 3D view clears every slice of its mip 1355 out.first_layer = volume ? 0 : image.first_layer; // a 3D view clears every slice of its mip
1138 out.layer_count = volume ? 1 : image.layer_count; 1356 out.layer_count = volume ? 1 : image.layer_count;
1357 out.exact_clear_format = volume || image.type == g::ImageType::image_1d ||
1358 image.type == g::ImageType::image_1d_array;
1139 return out.format != VK_FORMAT_UNDEFINED; 1359 return out.format != VK_FORMAT_UNDEFINED;
1140 } 1360 }
1141 g::BufferWords buffer_words{}; 1361 g::BufferWords buffer_words{};
@@ -1185,6 +1405,7 @@ private:
1185 if (layout && layout == state.layout) return; 1405 if (layout && layout == state.layout) return;
1186 hold(signature); // state.layout points into it 1406 hold(signature); // state.layout points into it
1187 state.layout = layout; 1407 state.layout = layout;
1408 if (layout && (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED)) directly_indexed_ = true;
1188 state.data = {}; 1409 state.data = {};
1189 // CreateRootSignature accepted it for the other bind point only (its log line says why). 1410 // CreateRootSignature accepted it for the other bind point only (its log line says why).
1190 if (layout && !(is_compute(state) ? layout->compute_ok : layout->graphics_ok)) { 1411 if (layout && !(is_compute(state) ? layout->compute_ok : layout->graphics_ok)) {
@@ -1239,9 +1460,20 @@ private:
1239 if ((count && !data) || std::uint64_t(offset) + count > p->constant_count) return check(false); 1460 if ((count && !data) || std::uint64_t(offset) + count > p->constant_count) return check(false);
1240 const auto* values = static_cast<const std::uint32_t*>(data); 1461 const auto* values = static_cast<const std::uint32_t*>(data);
1241 const std::uint32_t first = first_dword(state, *p); 1462 const std::uint32_t first = first_dword(state, *p);
1463 if (first == rt::rootsig::kNoSgpr) return spilled();
1242 for (UINT i = 0; i < count; ++i) write(state, first + offset + i, values[i]); 1464 for (UINT i = 0; i < count; ++i) write(state, first + offset + i, values[i]);
1243 } 1465 }
1244 1466
1467 // A parameter in the spill array behind s[0:1] (a compute signature past s31: pack_stage gives it no SGPR, only a
1468 // spill_dword): that array is not written yet, so its value is not stored; kNoSgpr plus an offset must never
1469 // reach write(), where it would wrap round to s0.
1470 static void spilled() {
1471 static std::atomic<bool> said{false};
1472 if (!said.exchange(true))
1473 std::fprintf(stderr, "[rt] d3d12: root arguments in the spill array behind s[0:1] are not stored (the "
1474 "array is not written yet)\n");
1475 }
1476
1245 void address(RootState& state, UINT index, std::uint64_t va, rt::rootsig::ParamType type) { 1477 void address(RootState& state, UINT index, std::uint64_t va, rt::rootsig::ParamType type) {
1246 if (list_.closed()) return; 1478 if (list_.closed()) return;
1247 if (defer([=, compute = &state == &compute_](GraphicsCommandList& l) { 1479 if (defer([=, compute = &state == &compute_](GraphicsCommandList& l) {
@@ -1250,11 +1482,27 @@ private:
1250 return; 1482 return;
1251 const RootArgumentLayout::Parameter* p = parameter(state, index, type); 1483 const RootArgumentLayout::Parameter* p = parameter(state, index, type);
1252 if (!p) return; 1484 if (!p) return;
1485 // A root view into the title's own memory (a slot-133 buffer, a constant ring) gets the console VA of a GPU
1486 // copy of it, so the shader's heap_base + VA reaches it (src/title_va_alias.h). A descriptor table is in one
1487 // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission.
1488 // A table in a console descriptor heap is read from the heap's arena copy (console_descriptor_table_va).
1489 if (type == rt::rootsig::ParamType::Descriptor)
1490 va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view);
1491 else
1492 va = console_descriptor_table_va(va);
1493 if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors) {
1494 if (!tables_.empty() && tables_.back().first == va)
1495 tables_.back().second = std::max(tables_.back().second, p->table_descriptors);
1496 else
1497 tables_.emplace_back(va, p->table_descriptors);
1498 }
1253 const std::uint32_t first = first_dword(state, *p); 1499 const std::uint32_t first = first_dword(state, *p);
1500 if (first == rt::rootsig::kNoSgpr) return spilled();
1254 write(state, first, std::uint32_t(va)); 1501 write(state, first, std::uint32_t(va));
1255 // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps 1502 // In the console layouts a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps
1256 // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. 1503 // live below 4 GiB); a root view keeps both halves. pack()'s graphics layout gives every address two dwords.
1257 if (!(is_compute(state) && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); 1504 const bool console = is_compute(state) || state.layout->graphics_console;
1505 if (!(console && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32));
1258 } 1506 }
1259 1507
1260 D3D12_COMMAND_LIST_TYPE type_; 1508 D3D12_COMMAND_LIST_TYPE type_;
@@ -1266,6 +1514,7 @@ private:
1266 RootState compute_; 1514 RootState compute_;
1267 RootState graphics_; 1515 RootState graphics_;
1268 std::uintptr_t compute_pipeline_ = 0; 1516 std::uintptr_t compute_pipeline_ = 0;
1517 bool unregistered_pipeline_ = false; // the bound PSO has no pipeline here (a stub): see set_pipeline
1269 std::uintptr_t graphics_pipeline_ = 0; 1518 std::uintptr_t graphics_pipeline_ = 0;
1270 ID3D12DescriptorHeap* cbv_srv_uav_heap_ = nullptr; 1519 ID3D12DescriptorHeap* cbv_srv_uav_heap_ = nullptr;
1271 ID3D12DescriptorHeap* sampler_heap_ = nullptr; 1520 ID3D12DescriptorHeap* sampler_heap_ = nullptr;
@@ -1274,8 +1523,19 @@ private:
1274 std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED 1523 std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED
1275 std::array<leonida::VertexBufferView, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> vertex_buffers_{}; 1524 std::array<leonida::VertexBufferView, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> vertex_buffers_{};
1276 leonida::IndexBufferView index_{}; 1525 leonida::IndexBufferView index_{};
1526 // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares
1527 std::vector<std::pair<std::uint64_t, std::uint32_t>> tables_;
1528 bool directly_indexed_ = false;
1529 // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes).
1530 static constexpr std::uint64_t kRootViewBytes = 65536;
1277 leonida::Viewport viewport_{}; 1531 leonida::Viewport viewport_{};
1278 leonida::Rect scissor_{}; 1532 leonida::Rect scissor_{};
1533 std::array<leonida::Viewport, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE> viewports_{};
1534 UINT viewport_count_ = 0;
1535 std::array<leonida::Rect, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE> scissors_{};
1536 UINT scissor_count_ = 0;
1537 std::shared_ptr<const leonida::DrawViewports> draw_viewports_;
1538 bool draw_viewports_stale_ = true;
1279 std::array<leonida::TargetView, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> render_targets_{}; 1539 std::array<leonida::TargetView, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> render_targets_{};
1280 UINT render_target_count_ = 0; 1540 UINT render_target_count_ = 0;
1281 // One block shared by every draw that keeps the same targets and buffers, rebuilt when either changes, so a 1541 // One block shared by every draw that keeps the same targets and buffers, rebuilt when either changes, so a
@@ -1331,7 +1591,11 @@ private:
1331 hold(state); 1591 hold(state);
1332 compute_pipeline_ = compute_pipeline_id(state); 1592 compute_pipeline_ = compute_pipeline_id(state);
1333 graphics_pipeline_ = graphics_pipeline_id(state); 1593 graphics_pipeline_ = graphics_pipeline_id(state);
1334 if (state && !compute_pipeline_ && !graphics_pipeline_) 1594 // A pipeline this device never registered: a LEONIDA_STUB_PIPELINES stub (its translated shader is missing),
1595 // or one from another device. Its draws resolve to nothing in replay; its dispatches are no-ops too
1596 // (record_dispatch), so the list still closes.
1597 unregistered_pipeline_ = state && !compute_pipeline_ && !graphics_pipeline_;
1598 if (unregistered_pipeline_)
1335 stub("ID3D12GraphicsCommandList::SetPipelineState(pipeline from another device)"); 1599 stub("ID3D12GraphicsCommandList::SetPipelineState(pipeline from another device)");
1336 } 1600 }
1337 1601
@@ -1355,13 +1619,13 @@ private:
1355 if (!cbv_srv_uav_heap_) 1619 if (!cbv_srv_uav_heap_)
1356 note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); 1620 note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound");
1357 else 1621 else
1358 note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); 1622 note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list");
1359 } 1623 }
1360 if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { 1624 if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) {
1361 if (!sampler_heap_) 1625 if (!sampler_heap_)
1362 note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); 1626 note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound");
1363 else 1627 else
1364 note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); 1628 note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list");
1365 } 1629 }
1366 } 1630 }
1367 1631
@@ -1378,6 +1642,12 @@ private:
1378 index_ = {}; 1642 index_ = {};
1379 viewport_ = {}; 1643 viewport_ = {};
1380 scissor_ = {}; 1644 scissor_ = {};
1645 viewports_.fill({});
1646 viewport_count_ = 0;
1647 scissors_.fill({});
1648 scissor_count_ = 0;
1649 draw_viewports_.reset();
1650 draw_viewports_stale_ = true;
1381 render_targets_.fill({}); 1651 render_targets_.fill({});
1382 render_target_count_ = 0; 1652 render_target_count_ = 0;
1383 draw_views_stale_ = true; 1653 draw_views_stale_ = true;
@@ -1388,21 +1658,130 @@ private:
1388 1658
1389 void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { 1659 void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) {
1390 if (count) draw_views_stale_ = true; 1660 if (count) draw_views_stale_ = true;
1391 for (UINT i = 0; i < count; ++i) 1661 for (UINT i = 0; i < count; ++i) {
1662 if (views) leonida::title_va_aliases().note(views[i].BufferLocation, leonida::TitleVaAliases::vertex_view);
1663 if (views) leonida::title_va_aliases().want_buffer(views[i].BufferLocation, views[i].SizeInBytes);
1392 vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, 1664 vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes,
1393 views[i].StrideInBytes} 1665 views[i].StrideInBytes}
1394 : leonida::VertexBufferView{}; 1666 : leonida::VertexBufferView{};
1667 }
1395 } 1668 }
1396 1669
1397 void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) { 1670 void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) {
1671 if (view) leonida::title_va_aliases().note(view->BufferLocation, leonida::TitleVaAliases::index_view);
1672 if (view) leonida::title_va_aliases().want_buffer(view->BufferLocation, view->SizeInBytes);
1398 index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} 1673 index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)}
1399 : leonida::IndexBufferView{}; 1674 : leonida::IndexBufferView{};
1400 } 1675 }
1401 1676
1402 void record_dispatch(UINT x, UINT y, UINT z) { 1677 // The compiled console ABI appends directly indexed heaps after the explicit root arguments: the resource heap's
1403 if (!compute_pipeline_ || !compute_.layout) return check(false); 1678 // 32-bit shader VA, then the sampler heap's, each only when the signature has its flag. `slot` is the first
1679 // dword after the arguments (RootArgumentLayout::*_arguments_end). The heaps are snapshotted for each command,
1680 // so rebinding a heap cannot change a recorded draw or dispatch.
1681 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> with_direct_heaps(const RootState& state,
1682 std::uint32_t slot) const {
1683 auto data = state.data;
1684 const auto flags = state.layout->flags;
1685 if ((flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) && slot < data.size())
1686 data[slot++] = static_cast<std::uint32_t>(cbv_srv_uav_base_);
1687 if ((flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) && slot < data.size())
1688 data[slot] = static_cast<std::uint32_t>(sampler_base_);
1689 return data;
1690 }
1691
1692 static bool direct_heaps_enabled(const char* variable) {
1693 const char* v = std::getenv(variable);
1694 return !(v && std::string_view(v) == "0");
1695 }
1696
1697 // Direct and indirect dispatches. Putting the resource heap first and the sampler heap next is a hypothesis
1698 // with partial evidence (docs/d3d12_vulkan.md section 3.4, tools/compute_heap_layout_census.py). A heap with no
1699 // inline user-data dword left is reported once per heap kind and the explicit arguments are kept.
1700 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> compute_user_data() const {
1404 note_direct_heap_indexing(compute_.layout); 1701 note_direct_heap_indexing(compute_.layout);
1405 check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); 1702 static const bool enabled = direct_heaps_enabled("LEONIDA_COMPUTE_DIRECT_HEAPS");
1703 if (!enabled) return compute_.data;
1704 const RootArgumentLayout& layout = *compute_.layout;
1705 const bool resource = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED;
1706 const bool sampler = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
1707 const std::uint32_t end = layout.compute_arguments_end;
1708 if ((resource || sampler) && end == rt::rootsig::kNoSgpr) {
1709 note_once("compute direct heaps: not supplied, the root arguments spill (no measured slot)");
1710 } else {
1711 if (resource && end >= rt::rootsig::kMaxUserSgprs)
1712 note_once("compute root arguments leave no inline SGPR for the resource heap");
1713 if (sampler && end + (resource ? 1u : 0u) >= rt::rootsig::kMaxUserSgprs)
1714 note_once("compute root arguments leave no inline SGPR for the sampler heap");
1715 }
1716 return with_direct_heaps(compute_, end);
1717 }
1718
1719 // Graphics: vertex, pixel and geometry shaders share one user-data block and the s8 layout, so the heaps after
1720 // the explicit arguments serve every one of those stages (a pixel shader of a signature whose arguments end at
1721 // s11 reads the resource heap from s11). A mesh shader reads push dword d as s(d + 8) through its root window
1722 // (RootArgumentLayout::mesh_ok), so the same dwords give it the heaps after its arguments from s16, where the
1723 // console puts them (issue #14 comment 7143020922, RT-DIRECT-HEAP-GRAPHICS); DispatchMesh reports a heap that
1724 // falls past the window. LEONIDA_GRAPHICS_DIRECT_HEAPS=0 restores the previous arguments.
1725 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> graphics_user_data() const {
1726 constexpr UINT direct = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED |
1727 D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
1728 const RootArgumentLayout& layout = *graphics_.layout;
1729 if (!(layout.flags & direct)) return graphics_.data;
1730 static const bool enabled = direct_heaps_enabled("LEONIDA_GRAPHICS_DIRECT_HEAPS");
1731 if (!enabled) {
1732 note_once("graphics direct heaps: off (LEONIDA_GRAPHICS_DIRECT_HEAPS=0), draws keep the explicit "
1733 "arguments only");
1734 return graphics_.data;
1735 }
1736 const std::uint32_t end = layout.graphics_arguments_end;
1737 if (end >= rt::rootsig::kMaxUserSgprs) {
1738 note_once(layout.graphics_console
1739 ? "graphics direct heaps: not supplied, the explicit arguments fill s8..s31"
1740 : "graphics direct heaps: not supplied, the signature keeps the s0 graphics layout");
1741 return graphics_.data;
1742 }
1743 static std::atomic<bool> logged{false};
1744 if (!logged.exchange(true, std::memory_order_relaxed)) {
1745 const bool resource = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED;
1746 const bool sampler = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
1747 char resource_at[48] = "none", sampler_at[48] = "none";
1748 if (resource)
1749 std::snprintf(resource_at, sizeof resource_at, "0x%llx at s%u",
1750 static_cast<unsigned long long>(std::uint32_t(cbv_srv_uav_base_)), end);
1751 if (sampler && end + (resource ? 1u : 0u) < rt::rootsig::kMaxUserSgprs)
1752 std::snprintf(sampler_at, sizeof sampler_at, "0x%llx at s%u",
1753 static_cast<unsigned long long>(std::uint32_t(sampler_base_)),
1754 end + (resource ? 1u : 0u));
1755 std::fprintf(stderr,
1756 "[rt] d3d12: graphics direct heaps: resource heap %s, sampler heap %s, after %u dwords of "
1757 "explicit arguments from s8 (first draw; LEONIDA_GRAPHICS_DIRECT_HEAPS=0 restores the "
1758 "old arguments)\n",
1759 resource_at, sampler_at, end - 8);
1760 }
1761 return with_direct_heaps(graphics_, end);
1762 }
1763
1764 void record_dispatch(UINT x, UINT y, UINT z) {
1765 if (!compute_pipeline_ && unregistered_pipeline_) return; // a stub pipeline's dispatch: nothing to run
1766 if (!compute_pipeline_) return check(false); // separate lines: the rejection log names which
1767 if (!compute_.layout) return check(false);
1768 static const bool probe = std::getenv("LEONIDA_COMPUTE_INPUTS") != nullptr;
1769 if (probe) {
1770 static std::mutex mutex;
1771 static std::set<std::tuple<std::uintptr_t, const RootArgumentLayout*, UINT64>> seen;
1772 std::lock_guard lock(mutex);
1773 if (seen.emplace(compute_pipeline_, compute_.layout, cbv_srv_uav_base_).second) {
1774 std::fprintf(stderr, "[rt] compute-layout: pso=%p flags=%x bound-heap=0x%llx shader-heap=0x%llx",
1775 reinterpret_cast<void*>(compute_pipeline_), compute_.layout->flags,
1776 (unsigned long long)cbv_srv_uav_base_,
1777 (unsigned long long)console_descriptor_table_va(cbv_srv_uav_base_));
1778 for (const auto& p : compute_.layout->parameters)
1779 std::fprintf(stderr, " (s%u type=%u const=%u slots=%u)", p.compute_offset,
1780 unsigned(p.type), p.constant_count, p.table_descriptors);
1781 std::fputc('\n', stderr);
1782 }
1783 }
1784 check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z}));
1406 } 1785 }
1407 1786
1408 // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. 1787 // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change.
@@ -1418,16 +1797,117 @@ private:
1418 return draw_views_; 1797 return draw_views_;
1419 } 1798 }
1420 1799
1800 bool any_nonempty_viewport() const {
1801 for (UINT i = 0; i < viewport_count_; ++i)
1802 if (viewports_[i].width > 0.0f && viewports_[i].height > 0.0f) return true;
1803 return false;
1804 }
1805
1806 std::shared_ptr<const leonida::DrawViewports> draw_viewports() {
1807 if (viewport_count_ <= 1 && scissor_count_ <= 1) return nullptr;
1808 if (draw_viewports_stale_) {
1809 auto block = std::make_shared<leonida::DrawViewports>();
1810 block->viewports = viewports_;
1811 block->viewport_count = viewport_count_;
1812 block->scissors = scissors_;
1813 block->scissor_count = scissor_count_;
1814 draw_viewports_ = std::move(block);
1815 draw_viewports_stale_ = false;
1816 }
1817 return draw_viewports_;
1818 }
1819
1421 // A draw needs a graphics pipeline, a graphics root signature and a topology. 1820 // A draw needs a graphics pipeline, a graphics root signature and a topology.
1422 void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { 1821 void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) {
1423 if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); 1822 if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false);
1424 note_direct_heap_indexing(graphics_.layout); 1823 note_direct_heap_indexing(graphics_.layout);
1425 // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, 1824 // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes
1426 // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. 1825 // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded.
1427 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; 1826 // LOCAL DIAGNOSTIC: the state each draw is recorded with
1428 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_, 1827 if (leonida::local_diagnostics()) {
1828 static std::atomic<std::uint64_t> draws{0}, skipped{0};
1829 const bool skip = !any_nonempty_viewport();
1830 const std::uint64_t n = ++draws, k = skip ? ++skipped : skipped.load();
1831 if (n <= 8 || n % 1200 == 0)
1832 std::fprintf(stderr, "[rt] present-probe: draw #%llu (%s; %llu skipped so far) pso %p rts %u rt0 0x%llx "
1833 "mip %u viewport %.0fx%.0f at %.0f,%.0f scissor %d,%d-%d,%d count %u x%u\n",
1834 static_cast<unsigned long long>(n), skip ? "SKIPPED: no viewport" : "recorded",
1835 static_cast<unsigned long long>(k), reinterpret_cast<const void*>(graphics_pipeline_),
1836 render_target_count_, static_cast<unsigned long long>(render_targets_[0].resource),
1837 render_targets_[0].mip, viewport_.width, viewport_.height, viewport_.x, viewport_.y,
1838 scissor_.left, scissor_.top, scissor_.right, scissor_.bottom, count, instances);
1839 // LOCAL DIAGNOSTIC (fsdraw): the first draw of each pipeline, and one frame's draws every ~300 frames,
1840 // with the pipeline's description, the root data and what the bound descriptor tables hold.
1841 static std::mutex seen_mutex;
1842 static std::set<std::uintptr_t> seen;
1843 bool first_seen;
1844 {
1845 std::lock_guard lock(seen_mutex);
1846 first_seen = seen.insert(graphics_pipeline_).second;
1847 }
1848 const bool fullscreen = render_target_count_ >= 1 && count == 3 && viewport_.width >= 1000;
1849 if (fullscreen) leonida::fsdraw::note_target(render_targets_[0].resource);
1850 if (first_seen || (n - 1) % 600 < 2 || (n > 2 && n < 9)) {
1851 std::fprintf(stderr, "[rt] fsdraw: draw #%llu pso %p%s rt0 0x%llx rts %u depth 0x%llx count %u x%u: %s\n",
1852 static_cast<unsigned long long>(n), reinterpret_cast<const void*>(graphics_pipeline_),
1853 first_seen ? " (first use)" : "", static_cast<unsigned long long>(render_targets_[0].resource),
1854 render_target_count_, static_cast<unsigned long long>(depth_.resource), count, instances,
1855 leonida::fsdraw::pipeline(graphics_pipeline_).c_str());
1856 std::fprintf(stderr, "[rt] fsdraw: draw #%llu layout %p user data [%s] cbv heap %p base 0x%llx sampler "
1857 "base 0x%llx tables %zu\n",
1858 static_cast<unsigned long long>(n), static_cast<const void*>(graphics_.layout),
1859 leonida::fsdraw::hex_words(graphics_.data.data(), graphics_.data.size()).c_str(),
1860 static_cast<const void*>(cbv_srv_uav_heap_),
1861 static_cast<unsigned long long>(cbv_srv_uav_base_),
1862 static_cast<unsigned long long>(sampler_base_), tables_.size());
1863 for (std::size_t slot = 0; slot < 2; ++slot) { // the vertex buffers the blit's VS reads
1864 const auto& vb = vertex_buffers_[slot];
1865 if (!vb.va) continue;
1866 std::uint32_t words[12]{};
1867 bool read = false;
1868 MEMORY_BASIC_INFORMATION mbi{};
1869 if (vb.va < leonida::fsdraw::arena_size()) {
1870 read = leonida::fsdraw::arena_words(vb.va, words, 12);
1871 } else if (VirtualQuery(reinterpret_cast<const void*>(static_cast<std::uintptr_t>(vb.va)), &mbi, sizeof mbi) &&
1872 mbi.State == MEM_COMMIT && !(mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && mbi.Protect) {
1873 std::memcpy(words, reinterpret_cast<const void*>(static_cast<std::uintptr_t>(vb.va)), sizeof words);
1874 read = true;
1875 }
1876 std::fprintf(stderr, "[rt] fsdraw: draw #%llu vb%zu va 0x%llx size %u stride %u: %s [%s]\n",
1877 static_cast<unsigned long long>(n), slot, static_cast<unsigned long long>(vb.va),
1878 unsigned(vb.size), unsigned(vb.stride), read ? "read" : "unreadable",
1879 read ? leonida::fsdraw::hex_words(words, 12).c_str() : "");
1880 }
1881 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
1882 std::uintptr_t heap_cpu = 0;
1883 if (cbv_srv_uav_heap_) {
1884 heap_desc = cbv_srv_uav_heap_->GetDesc();
1885 heap_cpu = cbv_srv_uav_heap_->GetCPUDescriptorHandleForHeapStart().ptr;
1886 }
1887 char tag[48];
1888 std::snprintf(tag, sizeof tag, "draw #%llu", static_cast<unsigned long long>(n));
1889 for (const auto& [shader_va, slots] : tables_) {
1890 const std::uint64_t va = leonida::fsdraw::table_origin(shader_va);
1891 const std::uint64_t end = cbv_srv_uav_base_ + std::uint64_t(heap_desc.NumDescriptors) * 32;
1892 const bool in_heap = heap_cpu && va >= cbv_srv_uav_base_ && va + 32 <= end;
1893 const auto* cpu = in_heap ? reinterpret_cast<const std::uint8_t*>(heap_cpu + (va - cbv_srv_uav_base_))
1894 : nullptr;
1895 const bool console = heap_cpu == std::uintptr_t(cbv_srv_uav_base_);
1896 if (shader_va != va)
1897 std::fprintf(stderr, "[rt] fsdraw: %s table title va 0x%llx is shader va 0x%llx\n", tag,
1898 static_cast<unsigned long long>(va), static_cast<unsigned long long>(shader_va));
1899 leonida::fsdraw::describe_table(tag, shader_va, slots, cpu,
1900 !in_heap ? "none (not in the bound CBV/SRV/UAV heap)"
1901 : console ? "console (CPU address = GPU VA, title memory)"
1902 : "layer heap (arena)");
1903 }
1904 }
1905 }
1906 if (!any_nonempty_viewport()) return;
1907 leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, index_, topology_, viewport_,
1429 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, 1908 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances,
1430 first, base_vertex, first_instance}; 1909 first, base_vertex, first_instance};
1910 draw.viewports = draw_viewports();
1431 check(list_.draw(std::move(draw))); 1911 check(list_.draw(std::move(draw)));
1432 } 1912 }
1433}; 1913};
@@ -1479,12 +1959,14 @@ public:
1479 context_.enqueue_fence_callback(semaphore, queued, [context, semaphore, queued, value, held = held_] { 1959 context_.enqueue_fence_callback(semaphore, queued, [context, semaphore, queued, value, held = held_] {
1480 std::uint64_t now = 0; 1960 std::uint64_t now = 0;
1481 bool signaled = false; 1961 bool signaled = false;
1482 if (context->vk.vkGetSemaphoreCounterValue(context->device(), semaphore, &now) == VK_SUCCESS && 1962 if (context->observe_result(context->vk.vkGetSemaphoreCounterValue(context->device(), semaphore, &now),
1963 "vkGetSemaphoreCounterValue (fence callback)") == VK_SUCCESS &&
1483 now >= queued && now < value) { 1964 now >= queued && now < value) {
1484 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 1965 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
1485 info.semaphore = semaphore; 1966 info.semaphore = semaphore;
1486 info.value = value; 1967 info.value = value;
1487 signaled = context->vk.vkSignalSemaphore(context->device(), &info) == VK_SUCCESS; 1968 signaled = context->observe_result(context->vk.vkSignalSemaphore(context->device(), &info),
1969 "vkSignalSemaphore (fence callback)") == VK_SUCCESS;
1488 } 1970 }
1489 held->fetch_sub(1); 1971 held->fetch_sub(1);
1490 if (signaled) { 1972 if (signaled) {
@@ -1654,6 +2136,83 @@ public:
1654 recorded.push_back(&list->commands()); 2136 recorded.push_back(&list->commands());
1655 graphics.push_back(list); 2137 graphics.push_back(list);
1656 } 2138 }
2139 if (!context_.publish_cpu_textures()) {
2140 last_result_=leonida::ReplayResult::unresolved_resource;
2141 d3d12_trace::record(method,"failed");
2142 return;
2143 }
2144 // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's
2145 // console VA before the copies are refreshed for this submission (src/title_va_alias.h).
2146 {
2147 std::map<std::uint64_t, std::uint32_t> tables; // each table once, with the most slots it was bound with
2148 for (const GraphicsCommandList* list : graphics)
2149 for (const auto& [table, descriptors] : list->tables())
2150 tables[table] = std::max(tables[table], descriptors);
2151 // LOCAL DIAGNOSTIC (fsdraw): poke experiment, LEONIDA_FSDRAW_POKE_CB=1
2152 if (leonida::fsdraw::poke_enabled()) {
2153 for (const auto& [table, descriptors] : tables) {
2154 const std::uint64_t origin = leonida::fsdraw::table_origin(table);
2155 if (origin != table)
2156 leonida::fsdraw::poke_cb(
2157 reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(origin)));
2158 }
2159 }
2160 // LOCAL DIAGNOSTIC (fsdraw): what the bound tables hold when the lists are submitted
2161 if (leonida::local_diagnostics()) {
2162 static std::atomic<std::uint64_t> submits{0};
2163 const std::uint64_t n = tables.empty() ? 0 : ++submits;
2164 if (n && (n <= 6 || n % 300 == 0)) {
2165 char tag[48];
2166 std::snprintf(tag, sizeof tag, "submit #%llu", static_cast<unsigned long long>(n));
2167 for (const auto& [table, descriptors] : tables) {
2168 const std::uint64_t origin = leonida::fsdraw::table_origin(table);
2169 const bool title = origin != table;
2170 leonida::fsdraw::describe_table(
2171 tag, table, descriptors,
2172 title ? reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(origin)) : nullptr,
2173 title ? "title memory (CPU bytes read at the title VA the table was set with)" : "arena or unknown");
2174 }
2175 }
2176 }
2177 if (!tables.empty()) {
2178 const auto start = std::chrono::steady_clock::now();
2179 for (const auto& [table, descriptors] : tables) {
2180 // A table VA is an offset in this device's arena, so its own scanner reads it; the process-wide
2181 // hook belongs to the first device that registered and serves a context without a scanner.
2182 if (!context_.scan_table(table, descriptors))
2183 leonida::title_va_aliases().scan_table(table, descriptors);
2184 if (!context_.prepare_sample_table(table, descriptors)) {
2185 last_result_ = leonida::ReplayResult::unresolved_resource;
2186 d3d12_trace::record(method, "failed");
2187 return;
2188 }
2189 }
2190 leonida::title_va_aliases().note_scan(std::uint64_t(
2191 std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start)
2192 .count()));
2193 }
2194 }
2195 for (const auto* list : graphics) {
2196 for (const auto& command : list->commands().commands()) {
2197 leonida::ResourceId resource = 0;
2198 if (const auto* b=std::get_if<leonida::TransitionBarrier>(&command)) {
2199 if (b->after & (D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE|D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE))
2200 resource=b->resource;
2201 } else if (const auto* b=std::get_if<leonida::TextureBarrier>(&command)) {
2202 if (b->access_after & D3D12_BARRIER_ACCESS_SHADER_RESOURCE) resource=b->resource;
2203 }
2204 if (resource && !context_.prepare_sample_table(resource,0)) {
2205 last_result_=leonida::ReplayResult::unresolved_resource;
2206 d3d12_trace::record(method,"failed");
2207 return;
2208 }
2209 }
2210 if (list->needs_all_sampled_views() && !context_.prepare_sample_table(0,0)) {
2211 last_result_ = leonida::ReplayResult::unresolved_resource;
2212 d3d12_trace::record(method,"failed");
2213 return;
2214 }
2215 }
1657 last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); 2216 last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); });
1658 d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); 2217 d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed");
1659 if (last_result_ != leonida::ReplayResult::success) 2218 if (last_result_ != leonida::ReplayResult::success)
@@ -1668,7 +2227,7 @@ public:
1668 for (const auto& command : list.commands().commands()) { 2227 for (const auto& command : list.commands().commands()) {
1669 const auto range = leonida::query_range(command); 2228 const auto range = leonida::query_range(command);
1670 if (range.count && range.type == leonida::d3d12_query::timestamp && 2229 if (range.count && range.type == leonida::d3d12_query::timestamp &&
1671 context_.query_heap_type(range.heap) == other) 2230 (!timestamp_family_supported() || context_.query_heap_type(range.heap) == other))
1672 return false; 2231 return false;
1673 } 2232 }
1674 return true; 2233 return true;
@@ -1727,16 +2286,20 @@ public:
1727 } 2286 }
1728 2287
1729 // Ticks per second of the timestamps EndQuery writes: one tick is timestampPeriod nanoseconds. Every D3D12 2288 // Ticks per second of the timestamps EndQuery writes: one tick is timestampPeriod nanoseconds. Every D3D12
1730 // queue of the device shares one VkQueue, so they share one frequency. E_FAIL when that queue has no 2289 // device has one timestamp period, but individual queue families may not write timestamps.
1731 // timestamps (timestampValidBits 0), as D3D12 reports for a queue that does not support them.
1732 HRESULT STDMETHODCALLTYPE GetTimestampFrequency(UINT64* frequency) override { 2290 HRESULT STDMETHODCALLTYPE GetTimestampFrequency(UINT64* frequency) override {
1733 if (!frequency) return E_INVALIDARG; 2291 if (!frequency) return E_INVALIDARG;
1734 const double period = context_.timestamp_period(); 2292 const double period = context_.timestamp_period();
1735 if (!(period > 0)) return E_FAIL; 2293 if (!(period > 0) || !timestamp_family_supported()) return E_FAIL;
1736 *frequency = static_cast<UINT64>(1e9 / period + 0.5); 2294 *frequency = static_cast<UINT64>(1e9 / period + 0.5);
1737 return S_OK; 2295 return S_OK;
1738 } 2296 }
1739 2297
2298 bool timestamp_family_supported() const {
2299 // The low-level queue factory also accepts caller-owned queues without a QueueClock.
2300 return !clock_.get_device_proc || clock_.timestamp_valid_bits != 0;
2301 }
2302
1740 // Queue labels, in order with the submissions around them. 2303 // Queue labels, in order with the submissions around them.
1741 void STDMETHODCALLTYPE SetMarker(UINT metadata, const void* data, UINT size) override { 2304 void STDMETHODCALLTYPE SetMarker(UINT metadata, const void* data, UINT size) override {
1742 d3d12_trace::record("ID3D12CommandQueue::SetMarker"); 2305 d3d12_trace::record("ID3D12CommandQueue::SetMarker");
@@ -1802,16 +2365,20 @@ private:
1802 LARGE_INTEGER before{}, after{}; 2365 LARGE_INTEGER before{}, after{};
1803 { 2366 {
1804 std::lock_guard submit_lock(context_.submit_mutex()); 2367 std::lock_guard submit_lock(context_.submit_mutex());
1805 if (vk.vkQueueWaitIdle(vk_queue_) != VK_SUCCESS) return E_FAIL; 2368 if (context_.observe_result(vk.vkQueueWaitIdle(vk_queue_), "vkQueueWaitIdle (calibration)") != VK_SUCCESS)
2369 return E_FAIL;
1806 QueryPerformanceCounter(&before); 2370 QueryPerformanceCounter(&before);
1807 if (vk.vkQueueSubmit(vk_queue_, 1, &submit, VK_NULL_HANDLE) != VK_SUCCESS || 2371 if (context_.observe_result(vk.vkQueueSubmit(vk_queue_, 1, &submit, VK_NULL_HANDLE),
1808 vk.vkQueueWaitIdle(vk_queue_) != VK_SUCCESS) 2372 "vkQueueSubmit (calibration)") != VK_SUCCESS ||
2373 context_.observe_result(vk.vkQueueWaitIdle(vk_queue_), "vkQueueWaitIdle (calibration)") != VK_SUCCESS)
1809 return E_FAIL; 2374 return E_FAIL;
1810 QueryPerformanceCounter(&after); 2375 QueryPerformanceCounter(&after);
1811 } 2376 }
1812 std::uint64_t stamp = 0; 2377 std::uint64_t stamp = 0;
1813 if (stamp_.get_query_pool_results(context_.device(), stamp_.queries, 0, 1, sizeof(stamp), &stamp, 2378 if (context_.observe_result(stamp_.get_query_pool_results(context_.device(), stamp_.queries, 0, 1,
1814 sizeof(stamp), VK_QUERY_RESULT_64_BIT) != VK_SUCCESS) 2379 sizeof(stamp), &stamp, sizeof(stamp),
2380 VK_QUERY_RESULT_64_BIT),
2381 "vkGetQueryPoolResults (calibration)") != VK_SUCCESS)
1815 return E_FAIL; 2382 return E_FAIL;
1816 if (clock_.timestamp_valid_bits < 64) stamp &= (std::uint64_t(1) << clock_.timestamp_valid_bits) - 1; 2383 if (clock_.timestamp_valid_bits < 64) stamp &= (std::uint64_t(1) << clock_.timestamp_valid_bits) - 1;
1817 gpu = stamp; 2384 gpu = stamp;
@@ -1944,6 +2511,11 @@ private:
1944 2511
1945} // namespace 2512} // namespace
1946 2513
2514bool record_gpu_label(ID3D12GraphicsCommandList* list,const leonida::label::Write& write) {
2515 auto* own=GraphicsCommandList::from(list);
2516 return own && own->xbox_label(write);
2517}
2518
1947HRESULT create_command_queue(leonida::VulkanContext& context, VkQueue queue, std::uint32_t queue_family, 2519HRESULT create_command_queue(leonida::VulkanContext& context, VkQueue queue, std::uint32_t queue_family,
1948 const D3D12_COMMAND_QUEUE_DESC& desc, REFIID riid, void** out, IUnknown* device, 2520 const D3D12_COMMAND_QUEUE_DESC& desc, REFIID riid, void** out, IUnknown* device,
1949 const QueueClock& clock, std::shared_ptr<void> queue_lease) { 2521 const QueueClock& clock, std::shared_ptr<void> queue_lease) {
@@ -2031,7 +2603,8 @@ HRESULT set_event_on_multiple_fence_completion(leonida::VulkanContext& context,
2031 wait.semaphoreCount = count; 2603 wait.semaphoreCount = count;
2032 wait.pSemaphores = semaphores.data(); 2604 wait.pSemaphores = semaphores.data();
2033 wait.pValues = values; 2605 wait.pValues = values;
2034 const VkResult result = context.vk.vkWaitSemaphores(context.device(), &wait, UINT64_MAX); 2606 const VkResult result = context.observe_result(
2607 context.vk.vkWaitSemaphores(context.device(), &wait, UINT64_MAX), "vkWaitSemaphores (multiple fences)");
2035 // Unlike a single fence's blocking SetEventOnCompletion, this path invokes Vulkan directly. 2608 // Unlike a single fence's blocking SetEventOnCompletion, this path invokes Vulkan directly.
2036 // A lost device must wake its other registered fence waiters and reject later submissions. 2609 // A lost device must wake its other registered fence waiters and reject later submissions.
2037 if (result == VK_ERROR_DEVICE_LOST) { 2610 if (result == VK_ERROR_DEVICE_LOST) {