From f893187d3425ae7b5648e58826fd426905aeb2ce Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:22:11 +0100 Subject: [PATCH 1/3] startup: record bound slot 57 targets with the creation capture --- CMakeLists.txt | 6 + docs/startup-runtime.md | 1 + src/startup_stubs/d3d12_capture.inl | 1 + src/startup_stubs/d3d12_draw.inl | 214 ++++++++++++++++++++---- src/startup_stubs/d3d12_xs_device.cpp | 40 ++++- tests/startup_indirect_draw_indexed.cpp | 139 ++++++++++++++- 6 files changed, 362 insertions(+), 39 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a5b4d5e5d5..ef621caf5b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1763,11 +1763,17 @@ set_tests_properties(startup_indirect_draw_indexed_hardware startup_indirect_dra startup_indirect_rectlist_hardware PROPERTIES SKIP_RETURN_CODE 77) foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_mesh_request_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + add_test(NAME startup_indirect_mesh57_targets_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + add_test(NAME startup_indirect_mesh57_targets_off_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) add_test(NAME startup_indirect_mesh_create_result_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(startup_indirect_mesh_create_result_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_FIXED_MESH_CREATE_FIXTURE=1") set_tests_properties(startup_indirect_mesh_request_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_MESH_REQUEST_FIXTURE=1") + set_tests_properties(startup_indirect_mesh57_targets_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_MESH_REQUEST_FIXTURE=1;X2W_TEST_MESH57_TARGETS=1") + set_tests_properties(startup_indirect_mesh57_targets_off_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_MESH_REQUEST_FIXTURE=1;X2W_TEST_MESH57_TARGETS=0") endforeach() add_test(NAME startup_missing_shader_fallback_warp COMMAND startup_indirect_draw_indexed warp missing-shader-fallback) add_test(NAME startup_missing_shader_fallback_off_warp COMMAND startup_indirect_draw_indexed warp missing-shader-fallback-off) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976e2f80ee..e0ace9affa 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1856,6 +1856,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first cache lookup the runtime starts a change feed on the directory (`ReadDirectoryChangesW`, top-level file names), then lists the directory's top-level file names once on the feed's thread and logs `x2w-draw cache index: names in ms; change feed ` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. The request-part and compute-marker probes (`req_` names, which only runtimes write) skip the disk for a name that is absent from the listing and from this process's own writes. The probes for `.txt` (graphics and compute manifests and the slot 57 base manifest) and `.cs.hlsl` skip it only while the change feed is reading and was reading before the listing began, so a file the translator writes later is found once its change record arrives. After a dropped batch or a feed error they use the disk again. A compute manifest retry (an absent, stale or unmarked `.txt`) whose `.*` names have no change record from the feed since its last miss repeats that miss without a file-system call; the feed records created, removed, renamed and rewritten files, and without a reading feed every retry looks on disk. Every 10 s while probes run, `x2w-draw cache probes (skipped as absent/on disk): ...` gives each probe's counts (and the compute retries repeated without I/O), the feed state, records and added names, the lookups that found a name added after the listing, and contradictions (a write that found a file the index had reported absent). | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_ALLOW_PUBLISHED_MESH57_PAIR=1` | opt-in, in render mode with `X2W_NATIVE_SHADERS`: permits the buffer-view slot 57 path to load a publisher's `.ms57.cso` / `.ps57.cso` pair after native translation refuses with the exact `mesh57_group_index` code. Native translation still runs first. Unset, the pair is ignored and that native refusal is rethrown before the manifest or a CSO is opened, including with `X2W_NATIVE_SHADERS_ONLY=1`. See [fixed mesh pipelines through slot 57](experiments/native-fixed-mesh57.md#published-pair-for-the-r1-group-index-exchange) | +| `X2W_MESH57_CAPTURE_STATE=1` | In `X2W_SHADER_CACHE`, archives [slot 57 creation state](experiments/native-fixed-mesh57.md) and queues `req_.t57` for matching-root indirect mesh calls with resolved attachments sharing one sample description. Each `targets dsv writable <0-or-1> samples ` line is one distinct tuple. Formats are decimal desktop DXGI view formats, with DSV format 0 for no depth view. The sidecar keeps up to eight tuples and adds an `overflow ` line once the cap is reached and another tuple is observed. Placeholder calls supply evidence for their creation variant as well. Background writes are best effort. | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 9e181eb612..12ef63a258 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -45,6 +45,7 @@ struct PipelineInfo { std::vector desc; std::vector state_a, state_b; // slot 57: the two state blocks, copied at creation (the title frees them) mutable FixedMeshBytes fixed_ms, fixed_ps; + mutable std::optional fixed_mesh_capture_variant; // retained after the request releases its stage copies mutable std::vector mesh57_pixel_spans; mutable UINT mesh57_heap_word = UINT_MAX; // R32_UINT at guest root constant[heap_word] & 1023. mutable std::vector mesh57_reads; // Host SRV register order. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2b012ca84d..ae07aba74b 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -256,13 +256,13 @@ u64 fnv_bytes(const void* data, std::size_t bytes, u64 hash = 146959810393466560 return hash; } -bool cache_path(wchar_t* out, const wchar_t* prefix, u64 key, const wchar_t* extension) +bool cache_path(wchar_t* out, const wchar_t* prefix, u64 key, const wchar_t* extension, bool require_fit = false) { wchar_t dir[MAX_PATH]; const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); if (!n || n >= MAX_PATH) return false; - swprintf(out, MAX_PATH, L"%s\\%s%016llx%s", dir, prefix, key, extension); - return true; + const int written = swprintf(out, MAX_PATH, L"%s\\%s%016llx%s", dir, prefix, key, extension); + return !require_fit || (written > 0 && written < MAX_PATH); } // X2W_SHADER_CACHE's top-level names (src/startup_stubs/cache_index.h). The first use starts the change feed, whose @@ -560,6 +560,21 @@ void write_cache_revision() if (!complete || !MoveFileExW(temporary, path, MOVEFILE_REPLACE_EXISTING)) DeleteFileW(temporary); } +bool publish_request_file(const wchar_t* path, const wchar_t* temporary, const void* data, std::size_t bytes, + DWORD move_flags, bool* already_existed = nullptr) +{ + HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + if (complete && MoveFileExW(temporary, path, move_flags)) return true; + DeleteFileW(temporary); + const bool exists = !move_flags && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; + if (already_existed) *already_existed = exists; + return exists; +} + // Publish each input atomically. The callers write the request's ready marker last. bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std::size_t bytes) { @@ -571,23 +586,12 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: if (!absent && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return true; swprintf(suffix, std::size(suffix), L"%s.%lu.tmp", ext, GetCurrentProcessId()); if (!cache_path(temporary, L"req_", key, suffix)) return false; - HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); - if (file == INVALID_HANDLE_VALUE) return false; - DWORD written = 0; - const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; - CloseHandle(file); - if (complete && MoveFileExW(temporary, path, 0)) { - note_cache_write(L"req_", key, ext); - return true; - } - DeleteFileW(temporary); - const bool exists = GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; - if (exists) { - // Another writer published the part after the listing; the index reported it absent. - if (absent) cache_index().count_contradiction(); - note_cache_write(L"req_", key, ext); - } - return exists; + bool already_existed = false; + if (!publish_request_file(path, temporary, data, bytes, 0, &already_existed)) return false; + // Another writer published the part after the listing; the index reported it absent. + if (already_existed && absent) cache_index().count_contradiction(); + note_cache_write(L"req_", key, ext); + return true; } bool native_shaders_only() @@ -1023,39 +1027,188 @@ u64 publish_compute_request(const void* desc) return key; } +constexpr unsigned mesh57_target_limit = 8; +LONG mesh57_target_writes_pending; + +struct Mesh57TargetWrite { + u64 variant; + HMODULE module = nullptr; + wchar_t path[MAX_PATH], temporary[MAX_PATH]; + UINT count; + DXGI_FORMAT rtvs[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; + DXGI_FORMAT dsv; + bool writable; + DXGI_SAMPLE_DESC samples; +}; + +bool write_mesh57_targets(const Mesh57TargetWrite& write) +{ + std::string tuple = "targets " + std::to_string(write.count); + for (UINT i = 0; i < write.count; ++i) + tuple += " " + std::to_string(static_cast(write.rtvs[i])); + tuple += " dsv " + std::to_string(static_cast(write.dsv)) + + " writable " + (write.writable ? "1" : "0") + + " samples " + std::to_string(write.samples.Count) + " " + std::to_string(write.samples.Quality); + + // Read the previous complete file, including observations from earlier runs in this cache. + // Refuse oversized or malformed files so a failed diagnostic never discards earlier evidence. + char buffer[2048]; + DWORD size = 0; + HANDLE file = CreateFileW(write.path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file != INVALID_HANDLE_VALUE) { + const bool complete = ReadFile(file, buffer, sizeof(buffer), &size, nullptr) && size < sizeof(buffer); + CloseHandle(file); + if (!complete) return false; + } else if (GetLastError() != ERROR_FILE_NOT_FOUND) { + return false; + } + const std::string_view old(buffer, size); + constexpr std::string_view overflow_prefix = "overflow "; + u64 overflow = 0; + unsigned count = 0; + std::size_t records_end = 0; + while (records_end < old.size()) { + const auto end = old.find('\n', records_end); + if (end == std::string_view::npos) return false; + const auto line = old.substr(records_end, end - records_end); + if (line.substr(0, overflow_prefix.size()) == overflow_prefix) { + if (count != mesh57_target_limit || end + 1 != old.size()) return false; + const auto* last = line.data() + line.size(); + const auto parsed = std::from_chars(line.data() + overflow_prefix.size(), last, overflow); + if (parsed.ec != std::errc{} || parsed.ptr != last) return false; + break; + } + if (line.substr(0, 8) != "targets " || ++count > mesh57_target_limit) return false; + if (line == tuple) return true; + records_end = end + 1; + } + std::string updated(old.substr(0, records_end)); + if (count < mesh57_target_limit) { + updated += tuple + '\n'; + } else { + if (overflow == ~u64{0}) return true; + updated += std::string(overflow_prefix) + std::to_string(overflow + 1) + '\n'; + } + return publish_request_file(write.path, write.temporary, updated.data(), updated.size(), MOVEFILE_REPLACE_EXISTING); +} + +void CALLBACK mesh57_targets_written(PTP_CALLBACK_INSTANCE instance, void* context) +{ + std::unique_ptr write(static_cast(context)); + FreeLibraryWhenCallbackReturns(instance, write->module); + // Serialize read/modify/replace for this variant, including other writers in this session. + // Only background workers wait on the mutex. + bool ok = false; + wchar_t name[64]; + swprintf(name, std::size(name), L"Local\\X2WMesh57Targets%016llx", write->variant); + if (const HANDLE mutex = CreateMutexW(nullptr, FALSE, name)) { + const DWORD wait = WaitForSingleObject(mutex, 5000); + if (wait == WAIT_OBJECT_0 || wait == WAIT_ABANDONED) { + try { + ok = write_mesh57_targets(*write); + } catch (const std::bad_alloc&) { + } + ReleaseMutex(mutex); + } + CloseHandle(mutex); + } + static LONG failures; + if (!ok && first_calls(failures, 12)) + log("x2w-draw fixed mesh targets %016llx could not be published", write->variant); + InterlockedDecrement(&mesh57_target_writes_pending); +} + +void capture_slot57_targets(Pass& pass) +{ + if (!pass.requested_mesh_variant || !pass.mesh57_targets_pending || !pass.targets_bound) return; + struct RestoreLastError { + DWORD saved = GetLastError(); + ~RestoreLastError() { SetLastError(saved); } + } restore_last_error; + DXGI_SAMPLE_DESC samples{}; + const auto collect_samples = [&samples](ID3D12Resource* resource) { + const auto desc = resource->GetDesc().SampleDesc; + if (!samples.Count) samples = desc; + return desc.Count && desc.Count == samples.Count && desc.Quality == samples.Quality; + }; + const auto typed = [](DXGI_FORMAT format) { + return format != DXGI_FORMAT_UNKNOWN && !x2w_view_dimension::typeless(static_cast(format)); + }; + for (UINT i = 0; i < pass.target_count; ++i) + if (!typed(pass.target_formats[i]) || !collect_samples(pass.bound_targets[i])) return; + if (pass.bound_depth && (!typed(pass.dsv_format) || !collect_samples(pass.bound_depth))) return; + if (!samples.Count) return; + + // Bound the outstanding diagnostics. A later draw of this recording can retry a declined submission. + constexpr LONG pending_limit = 256; + if (InterlockedIncrement(&mesh57_target_writes_pending) > pending_limit) { + InterlockedDecrement(&mesh57_target_writes_pending); + return; + } + auto* write = new (std::nothrow) Mesh57TargetWrite{}; + if (write) { + write->variant = *pass.requested_mesh_variant; + write->count = pass.target_count; + std::copy_n(pass.target_formats, pass.target_count, write->rtvs); + write->dsv = pass.dsv_format; + write->writable = pass.depth_view_writable; + write->samples = samples; + wchar_t suffix[32]; + swprintf(suffix, std::size(suffix), L".t57.%lu.tmp", GetCurrentProcessId()); + if (cache_path(write->path, L"req_", write->variant, L".t57", true) && + cache_path(write->temporary, L"req_", write->variant, suffix, true) && + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + reinterpret_cast(&mesh57_target_writes_pending), &write->module) && + TrySubmitThreadpoolCallback(mesh57_targets_written, write, nullptr)) { + pass.mesh57_targets_pending = false; + return; + } + if (write->module) FreeLibrary(write->module); + delete write; + } + InterlockedDecrement(&mesh57_target_writes_pending); +} + // Slot 57 fixed descriptors consumed by a decoded DispatchMesh signature. // The vertex span must be absent. A null/zero PS span is valid for depth-only work. -void request_slot57_mesh(Wrapper* pipeline, const std::vector* bound_root) +std::optional request_slot57_mesh(Wrapper* pipeline, const std::vector* bound_root, bool capture_state) { wchar_t marker[MAX_PATH]; - if (!bound_root || !cache_path(marker, L"req_", 0, L".m57")) return; + if (!bound_root || !cache_path(marker, L"req_", 0, L".m57")) return {}; const PipelineInfo* info = pipeline_info(pipeline); + const bool direct = info && info->path == 57; for (int depth = 0; info && info->path == 55 && info->base && depth < 8; ++depth) info = pipeline_info(info->base); constexpr std::size_t fields = 15; // through the MS length at +0x70 - if (!info || info->path != 57 || info->desc.size() < fields * sizeof(u64)) return; + if (!info || info->path != 57 || info->desc.size() < fields * sizeof(u64)) return {}; u64 words[fields]; std::memcpy(words, info->desc.data(), sizeof(words)); - if (words[9] || words[10]) return; // VS at +0x48 + if (words[9] || words[10]) return {}; // VS at +0x48 const Wrapper* root = as_wrapper(reinterpret_cast(words[0])); - if (!root || root_info(root) != bound_root) return; + if (!root || root_info(root) != bound_root) return {}; std::vector root_blob; { AcquireSRWLockShared(¬e_lock); if (const auto found = root_blobs().find(root); found != root_blobs().end()) root_blob = found->second; ReleaseSRWLockShared(¬e_lock); } - if (root_blob.empty()) return; + if (root_blob.empty()) return {}; static SRWLOCK request_lock = SRWLOCK_INIT; static std::unordered_set written; x2w_startup::ExclusiveNoteLock guard(request_lock); - if (!info->fixed_ms) return; + // A derived slot-55 pipeline can publish the base creation bytes, but its effective attachment + // signature is not evidence for the base variant. + const auto captured_variant = [&] { + return capture_state && direct ? info->fixed_mesh_capture_variant : std::optional{}; + }; + if (!info->fixed_ms) return captured_variant(); const auto& mesh = *info->fixed_ms; const std::vector empty; const auto& pixel = info->fixed_ps ? *info->fixed_ps : empty; const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(shader_cache::mesh57_revision, sizeof(shader_cache::mesh57_revision) - 1)))); - if (x2w_local::env_on("X2W_MESH57_CAPTURE_STATE") && + if (capture_state && !info->fixed_mesh_capture_variant && words[2] == info->state_a.size() && words[4] == info->state_b.size()) { // Payload: request key, three uint32 lengths, normalized descriptor, state A, state B. const auto desc = x2w_startup::normalize_mesh57_descriptor(info->desc); @@ -1067,7 +1220,9 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo std::memcpy(packed.data() + sizeof(key), lengths, sizeof(lengths)); for (const auto* bytes : {&desc, &info->state_a, &info->state_b}) packed.insert(packed.end(), bytes->begin(), bytes->end()); - if (!publish_shader_request(variant, L".s57", packed.data(), packed.size())) + if (publish_shader_request(variant, L".s57", packed.data(), packed.size())) + info->fixed_mesh_capture_variant = variant; + else log("x2w-draw fixed mesh state %016llx could not be published", variant); } const unsigned char none = 0; @@ -1082,6 +1237,7 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo info->fixed_ms.reset(); info->fixed_ps.reset(); } + return captured_variant(); } // The INPUT_LAYOUT subobject as the request text tools/startup/gfx2hlsl.py reads: "ia1 ", then one diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a3ddf5832..5d3965f4e3 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -116,6 +116,7 @@ #include #include #include +#include #include #include #include @@ -336,7 +337,9 @@ void log(const char* format, ...); bool first_calls(LONG& counter, LONG limit); void request_translation(Wrapper* pipeline); struct RootParameter; -void request_slot57_mesh(Wrapper* pipeline, const std::vector* bound_root); +struct Pass; +std::optional request_slot57_mesh(Wrapper* pipeline, const std::vector* bound_root, bool capture_state); +void capture_slot57_targets(Pass& pass); std::uint64_t accepted_view_heap_descriptors(ID3D12Device* device, UINT node_mask); std::uint64_t desktop_cpu_handle(std::uint64_t handle, UINT* contiguous = nullptr, UINT* available = nullptr, @@ -3511,6 +3514,8 @@ struct Pass { Wrapper* requested_pipeline = nullptr; // last pipeline slot 61 asked a translation for; repeats skip draw_lock Wrapper* requested_mesh_pipeline = nullptr; const std::vector* requested_mesh_root = nullptr; + std::optional requested_mesh_variant; + bool mesh57_targets_pending = false; UINT topology = 0; x2w_startup::ViewTable view_tables[16]{}; x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler @@ -4615,11 +4620,13 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const bool mesh = command == IndirectCommand::dispatch_mesh; const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); - if (mesh && pass.pipeline && pass.pipeline->own().real && x2w_local::env_on("X2W_MESH57_CAPTURE_STATE") && + const bool capture_mesh_state = mesh && pass.pipeline && x2w_local::env_on("X2W_MESH57_CAPTURE_STATE"); + if (capture_mesh_state && pass.pipeline->own().real && (pass.requested_mesh_pipeline != pass.pipeline || pass.requested_mesh_root != pass.root)) { pass.requested_mesh_pipeline = pass.pipeline; pass.requested_mesh_root = pass.root; - request_slot57_mesh(pass.pipeline, pass.root); + pass.requested_mesh_variant = request_slot57_mesh(pass.pipeline, pass.root, capture_mesh_state); + pass.mesh57_targets_pending = true; } refusal_pipeline = pass.pipeline; // A slot 62 builder pipeline is tracked by the wrapper itself, not by a slot 67 request key. @@ -4639,6 +4646,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (indexed) bytes = sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); + if (capture_mesh_state && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline->own().real) + capture_slot57_targets(pass); if (type != D3D12_COMMAND_LIST_TYPE_DIRECT || (!translated && (!pass.indirect_graphics.root || (pass.indirect_graphics.constant_guest == UINT_MAX && (pass.indirect_graphics.texture_map_root ? pass.indirect_graphics.texture_map_guest_root : @@ -4648,11 +4657,14 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, pass.indirect_graphics.mesh != mesh))) { // A console pipeline (no desktop pipeline) used only here still gets the request a direct draw writes; // nothing is drawn. - if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && - (pass.requested_mesh_pipeline != pass.pipeline || pass.requested_mesh_root != pass.root)) { - pass.requested_mesh_pipeline = pass.pipeline; - pass.requested_mesh_root = pass.root; - request_slot57_mesh(pass.pipeline, pass.root); + if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real) { + if (pass.requested_mesh_pipeline != pass.pipeline || pass.requested_mesh_root != pass.root) { + pass.requested_mesh_pipeline = pass.pipeline; + pass.requested_mesh_root = pass.root; + pass.requested_mesh_variant = request_slot57_mesh(pass.pipeline, pass.root, capture_mesh_state); + pass.mesh57_targets_pending = capture_mesh_state; + } + if (capture_mesh_state) capture_slot57_targets(pass); } else if (!mesh && pass.pipeline && !pass.pipeline->own().real && pass.requested_pipeline != pass.pipeline) { pass.requested_pipeline = pass.pipeline; request_translation(pass.pipeline); @@ -5400,6 +5412,7 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO pass.depth_view_writable = dsv_target && dsv_state == D3D12_RESOURCE_STATE_DEPTH_WRITE; list->OMSetRenderTargets(count, count ? desktop : nullptr, FALSE, dsv_ptr); pass.targets_bound = true; + if (pass.requested_mesh_variant) pass.mesh57_targets_pending = true; InterlockedIncrement(&render_target_binds); } // List slots 21 / 22 / 23, RSSetViewports / RSSetScissorRects / OMSetBlendFactor. @@ -7817,6 +7830,17 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, voi return TRUE; } +// Fixtures wait before reading or deleting their private capture directories. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_wait_mesh57_targets(DWORD timeout) +{ + const auto start = GetTickCount64(); + while (InterlockedCompareExchange(&mesh57_target_writes_pending, 0, 0)) { + if (GetTickCount64() - start >= timeout) return FALSE; + Sleep(1); + } + return TRUE; +} + // Fixture probe (startup_teardown_unload, #2572) for the four caches that keep desktop objects for a // device, one bit each: the indexed-validation pipeline (d3d12_draw.inl, bit 1) and the rectangle-list // argument converter (rect_indirect_args.h, bit 2), the placed page aliases of the translated indirect diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 02b7c56c32..760c4cb122 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -35,6 +35,7 @@ extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, extern "C" __declspec(dllimport) BOOL x2w_d3d12_distinct_rect_scratch(void*, void*); extern "C" __declspec(dllimport) std::size_t x2w_d3d12_census_report(char* out, std::size_t capacity); extern "C" __declspec(dllimport) void x2w_d3d12_mesh57_profile_stats(LONG* lookups, LONG* opens); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_fixture_wait_mesh57_targets(DWORD timeout); #if defined(OFFSCREEN_AGILITY_620) extern "C" { @@ -3032,6 +3033,7 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, false, 0, false, false, nullptr, nullptr, false, 2, &profile)) return 1; if (!ok) return 1; + check(x2w_d3d12_fixture_wait_mesh57_targets(5000) ? S_OK : E_FAIL, "wait for fixed mesh targets"); for (const auto i : {0, 1, 3, 5, 13}) fields[i] = 0; const UINT sizes[]{sizeof(fields), sizeof(expected_a), sizeof(expected_b)}; @@ -3063,6 +3065,128 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, return 0; } +bool mesh57_target_capture(ID3D12Device* device, ID3D12Device* guest, IUnknown* pipeline, + ID3D12RootSignature* root, ID3D12CommandSignature* signature, + const std::filesystem::path& cache, bool enabled) +{ + check(SetEnvironmentVariableA("X2W_MESH57_CAPTURE_STATE", enabled ? "1" : "0") ? S_OK : E_FAIL, + "configure slot 57 state capture"); + const D3D12_RESOURCE_DESC color_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + DXGI_FORMAT_R8G8B8A8_TYPELESS, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + auto depth_desc = color_desc; + depth_desc.Format = DXGI_FORMAT_R16_TYPELESS; + depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const auto color = resource(device, color_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + const auto depth = resource(device, depth_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 3}; + const D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2}; + ComPtr rtv_heap, dsv_heap; + check(guest->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap)), "create slot 57 RTV heap"); + check(guest->CreateDescriptorHeap(&dsv_heap_desc, IID_PPV_ARGS(&dsv_heap)), "create slot 57 DSV heap"); + using GetCpu = UINT64 (WINAPI*)(IUnknown*, void*); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv0{slot(rtv_heap.Get(), 9)(rtv_heap.Get(), nullptr)}; + const D3D12_CPU_DESCRIPTOR_HANDLE dsv0{slot(dsv_heap.Get(), 9)(dsv_heap.Get(), nullptr)}; + const auto rtv_stride = device->GetDescriptorHandleIncrementSize(rtv_heap_desc.Type); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv1{rtv0.ptr + rtv_stride}, rtv2{rtv1.ptr + rtv_stride}; + const D3D12_CPU_DESCRIPTOR_HANDLE dsv1{dsv0.ptr + device->GetDescriptorHandleIncrementSize(dsv_heap_desc.Type)}; + D3D12_RENDER_TARGET_VIEW_DESC rtv{}; + rtv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rtv.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + guest->CreateRenderTargetView(color.Get(), &rtv, rtv0); + rtv.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + guest->CreateRenderTargetView(color.Get(), &rtv, rtv1); + rtv.Format = DXGI_FORMAT_R8G8B8A8_UINT; + guest->CreateRenderTargetView(color.Get(), &rtv, rtv2); + D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; + dsv.Format = DXGI_FORMAT_D16_UNORM; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + guest->CreateDepthStencilView(depth.Get(), &dsv, dsv0); + dsv.Flags = D3D12_DSV_FLAG_READ_ONLY_DEPTH; + guest->CreateDepthStencilView(depth.Get(), &dsv, dsv1); + + using Bind = void (WINAPI*)(IUnknown*, IUnknown*); + using Targets = void (WINAPI*)(IUnknown*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, + const D3D12_CPU_DESCRIPTOR_HANDLE*); + using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + using Close = HRESULT (WINAPI*)(IUnknown*); + PlacedBuffer arguments(device, guest, sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), D3D12_RESOURCE_FLAG_NONE); + const auto observe = [&](IUnknown* list, D3D12_CPU_DESCRIPTOR_HANDLE color_view, + const D3D12_CPU_DESCRIPTOR_HANDLE* depth_view) { + slot(list, 50)(list, 1, &color_view, FALSE, depth_view); + slot(list, 61)(list, signature, 1, arguments.wrapped.Get(), 0, nullptr, 0); + }; + const auto compare = [&](const std::string& expected) { + check(x2w_d3d12_fixture_wait_mesh57_targets(5000) ? S_OK : E_FAIL, "wait for slot 57 target sidecar"); + std::filesystem::path archive, sidecar; + for (const auto& entry : std::filesystem::directory_iterator(cache)) { + if (entry.path().extension() == ".s57") { + if (!archive.empty()) return false; + archive = entry.path(); + } + if (entry.path().extension() == ".t57") { + if (!sidecar.empty()) return false; + sidecar = entry.path(); + } + } + if (!enabled) return archive.empty() && sidecar.empty(); + if (archive.empty() || archive.replace_extension(".t57") != sidecar) { + std::fputs("slot 57 target sidecar does not match the creation archive\n", stderr); + return false; + } + std::ifstream in(sidecar, std::ios::binary); + const std::string found(std::istreambuf_iterator(in), {}); + if (found == expected) return true; + std::fprintf(stderr, "slot 57 target sidecar expected:\n%sactual:\n%s", expected.c_str(), found.c_str()); + return false; + }; + ComPtr allocator, next_allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), + "create slot 57 target allocator"); + auto list = begin_guest_list(guest, allocator.Get()); + slot(list.Get(), 25)(list.Get(), pipeline); + slot(list.Get(), 34)(list.Get(), root); + const std::string first = "targets 1 28 dsv 0 writable 0 samples 1 0\n"; + const std::string second = "targets 1 29 dsv 55 writable 1 samples 1 0\n"; + const std::string read_only = "targets 1 29 dsv 55 writable 0 samples 1 0\n"; + observe(list.Get(), rtv0, nullptr); + observe(list.Get(), rtv0, nullptr); + if (!compare(first)) return false; + observe(list.Get(), rtv1, &dsv0); + if (!compare(first + second)) return false; + check(slot(list.Get(), 9)(list.Get()), "close first slot 57 target list"); + + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&next_allocator)), + "create next slot 57 target allocator"); + auto next = begin_guest_list(guest, next_allocator.Get()); + slot(next.Get(), 25)(next.Get(), pipeline); + slot(next.Get(), 34)(next.Get(), root); + observe(next.Get(), rtv1, &dsv1); + auto expected = first + second + read_only; + if (!compare(expected)) return false; + const struct { + D3D12_CPU_DESCRIPTOR_HANDLE color; + const D3D12_CPU_DESCRIPTOR_HANDLE* depth; + const char* line; + } remaining[]{ + {rtv0, &dsv0, "targets 1 28 dsv 55 writable 1 samples 1 0\n"}, + {rtv0, &dsv1, "targets 1 28 dsv 55 writable 0 samples 1 0\n"}, + {rtv1, nullptr, "targets 1 29 dsv 0 writable 0 samples 1 0\n"}, + {rtv2, nullptr, "targets 1 30 dsv 0 writable 0 samples 1 0\n"}, + {rtv2, &dsv0, "targets 1 30 dsv 55 writable 1 samples 1 0\n"}, + }; + for (const auto& extra : remaining) { + observe(next.Get(), extra.color, extra.depth); + expected += extra.line; + if (!compare(expected)) return false; + } + observe(next.Get(), rtv2, &dsv1); + if (!compare(expected + "overflow 1\n")) return false; + observe(next.Get(), rtv0, nullptr); // A retained tuple still deduplicates after saturation. + observe(next.Get(), rtv2, &dsv1); // The unretained bind adds another overflow observation. + check(slot(next.Get(), 9)(next.Get()), "close second slot 57 target list"); + return compare(expected + "overflow 2\n"); +} + int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; @@ -3475,12 +3599,16 @@ int main(int argc, char** argv) try return ok ? 0 : 1; } if (mesh && GetEnvironmentVariableA("X2W_MESH_REQUEST_FIXTURE", nullptr, 0)) { + char target_mode[2]{}; + const bool target_fixture = GetEnvironmentVariableA("X2W_TEST_MESH57_TARGETS", target_mode, sizeof(target_mode)) == 1; wchar_t exchange[MAX_PATH]{}; const DWORD exchange_size = GetEnvironmentVariableW(L"X2W_TEST_MESH57_EXCHANGE", exchange, MAX_PATH); if (exchange_size >= MAX_PATH) return 1; const auto cache = exchange_size ? std::filesystem::path(exchange) / "requests" : - std::filesystem::current_path() / ("slot57-mesh-" + std::to_string(GetCurrentProcessId())); - std::filesystem::create_directory(cache); + std::filesystem::current_path() / ("slot57-mesh-" + std::to_string(GetCurrentProcessId()) + + (target_fixture ? "-targets-" + std::to_string(GetTickCount64()) : "")); + const bool created_cache = std::filesystem::create_directory(cache); + if (target_fixture && !created_cache) return 1; check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()) ? S_OK : E_FAIL, "set mesh fixture cache"); const D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}; D3D12_ROOT_PARAMETER params[2]{}; @@ -3539,6 +3667,13 @@ int main(int argc, char** argv) try DrawKind::mesh, false, Refusal::none, label); }; const auto pair = make_pso(true, false, false); + if (target_fixture) { + if (!mesh57_target_capture(device.Get(), guest.Get(), pair.Get(), root.Get(), signature.Get(), + cache, target_mode[0] == '1')) return 1; + std::filesystem::remove_all(cache); + std::puts("slot 57 target sidecar fixture passed"); + return 0; + } const auto depth = make_pso(false, false, false); const auto aliased_vertex = make_pso(true, true, false); const auto incomplete = make_pso(true, false, true); From 09df3efa1e634d1df812ec1a1ffac28697150ac8 Mon Sep 17 00:00:00 2001 From: R0D4X Date: Tue, 1 Dec 2026 17:40:36 +0100 Subject: [PATCH 2/3] startup: skip slot 57 target capture on unresolved depth and expand fixture --- CMakePresets.json | 2 +- src/startup_stubs/d3d12_draw.inl | 2 +- src/startup_stubs/d3d12_xs_device.cpp | 61 ++++++++++++++----------- tests/startup_indirect_draw_indexed.cpp | 39 ++++++++++++++-- 4 files changed, 71 insertions(+), 33 deletions(-) diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..a0ec22a542 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -50,7 +50,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|mesh57_targets(_off)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index ae07aba74b..6a9b3bf049 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1121,7 +1121,7 @@ void CALLBACK mesh57_targets_written(PTP_CALLBACK_INSTANCE instance, void* conte void capture_slot57_targets(Pass& pass) { - if (!pass.requested_mesh_variant || !pass.mesh57_targets_pending || !pass.targets_bound) return; + if (!pass.requested_mesh_variant || !pass.mesh57_targets_pending || !pass.targets_bound || pass.depth_unresolved) return; struct RestoreLastError { DWORD saved = GetLastError(); ~RestoreLastError() { SetLastError(saved); } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 5d3965f4e3..506d4788ac 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3500,6 +3500,7 @@ struct Pass { IndirectGraphicsPipeline indirect_graphics; ID3D12RootSignature* graphics_root = nullptr; bool targets_bound = false; + bool depth_unresolved = false; bool topology_ok = false; unsigned srv_bound = 0; // bit per root parameter with a desktop address bound const std::vector* root = nullptr; @@ -5301,6 +5302,7 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO auto* list = recording(self); Pass& pass = pass_of(self); pass.targets_bound = false; + pass.depth_unresolved = false; pass.targets_single_sample = false; pass.depth_view_writable = false; pass.target_count = 0; @@ -5357,35 +5359,41 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO ID3D12Resource* dsv_target = nullptr; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; D3D12_RESOURCE_STATES dsv_state = D3D12_RESOURCE_STATE_DEPTH_WRITE; - if (depth && x2w_local::readable(depth, sizeof(*depth))) { - const u64 resolved = desktop_cpu_handle(depth->ptr); - if (!resolved) { - // The handle maps to no desktop descriptor: no depth is bound although the pipeline may expect one. - InterlockedIncrement(&render_target_unresolved); - if (first_calls(unresolved_logged, 6)) - log("x2w-d3d12 OMSetRenderTargets: depth handle 0x%llx maps to no descriptor; binding no depth", static_cast(depth->ptr)); + bool depth_unresolved = false; + if (depth) { + if (!x2w_local::readable(depth, sizeof(*depth))) { + depth_unresolved = true; } else { - const ResolvedView view = resolve_view(resolved, 21); - dsv_target = view.resource; - if (!dsv_target) { + const u64 resolved = desktop_cpu_handle(depth->ptr); + if (!resolved) { + // The handle maps to no desktop descriptor: no depth is bound although the pipeline may expect one. + depth_unresolved = true; InterlockedIncrement(&render_target_unresolved); - if (first_calls(refused, 6)) - log("x2w-d3d12 OMSetRenderTargets refused: depth handle is %s", - view.wrong_kind ? "not a depth stencil view" - : view.skipped ? "a skipped depth stencil view" : "not a known depth stencil view"); - return; - } - dsv_format = view_format_of(resolved, dsv_target); - const bool read_depth = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) != 0; - // A format without a stencil plane has no second plane to disagree with. - const bool read_stencil = !format_has_stencil(dsv_format) ? read_depth : (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0; - if (read_depth != read_stencil) { - if (first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: depth stencil view with one read-only plane (flags 0x%x)", view.dsv_flags); - return; + if (first_calls(unresolved_logged, 6)) + log("x2w-d3d12 OMSetRenderTargets: depth handle 0x%llx maps to no descriptor; binding no depth", static_cast(depth->ptr)); + } else { + const ResolvedView view = resolve_view(resolved, 21); + dsv_target = view.resource; + if (!dsv_target) { + InterlockedIncrement(&render_target_unresolved); + if (first_calls(refused, 6)) + log("x2w-d3d12 OMSetRenderTargets refused: depth handle is %s", + view.wrong_kind ? "not a depth stencil view" + : view.skipped ? "a skipped depth stencil view" : "not a known depth stencil view"); + return; + } + dsv_format = view_format_of(resolved, dsv_target); + const bool read_depth = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) != 0; + // A format without a stencil plane has no second plane to disagree with. + const bool read_stencil = !format_has_stencil(dsv_format) ? read_depth : (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0; + if (read_depth != read_stencil) { + if (first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: depth stencil view with one read-only plane (flags 0x%x)", view.dsv_flags); + return; + } + if (read_depth) dsv_state = D3D12_RESOURCE_STATE_DEPTH_READ; + desktop_dsv.ptr = static_cast(resolved); + dsv_ptr = &desktop_dsv; } - if (read_depth) dsv_state = D3D12_RESOURCE_STATE_DEPTH_READ; - desktop_dsv.ptr = static_cast(resolved); - dsv_ptr = &desktop_dsv; } } if (!count && !dsv_ptr) return; @@ -5410,6 +5418,7 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO pass.targets_single_sample = std::all_of(targets, targets + count, single_sample) && (!dsv_target || single_sample(dsv_target)); pass.depth_view_writable = dsv_target && dsv_state == D3D12_RESOURCE_STATE_DEPTH_WRITE; + pass.depth_unresolved = depth_unresolved; list->OMSetRenderTargets(count, count ? desktop : nullptr, FALSE, dsv_ptr); pass.targets_bound = true; if (pass.requested_mesh_variant) pass.mesh57_targets_pending = true; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 760c4cb122..70a6b72394 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -3077,8 +3077,11 @@ bool mesh57_target_capture(ID3D12Device* device, ID3D12Device* guest, IUnknown* depth_desc.Format = DXGI_FORMAT_R16_TYPELESS; depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; const auto color = resource(device, color_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + auto color_ms_desc = color_desc; + color_ms_desc.SampleDesc = {4, 0}; + const auto color_ms = resource(device, color_ms_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); const auto depth = resource(device, depth_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); - const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 3}; + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4}; const D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2}; ComPtr rtv_heap, dsv_heap; check(guest->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap)), "create slot 57 RTV heap"); @@ -3087,7 +3090,8 @@ bool mesh57_target_capture(ID3D12Device* device, ID3D12Device* guest, IUnknown* const D3D12_CPU_DESCRIPTOR_HANDLE rtv0{slot(rtv_heap.Get(), 9)(rtv_heap.Get(), nullptr)}; const D3D12_CPU_DESCRIPTOR_HANDLE dsv0{slot(dsv_heap.Get(), 9)(dsv_heap.Get(), nullptr)}; const auto rtv_stride = device->GetDescriptorHandleIncrementSize(rtv_heap_desc.Type); - const D3D12_CPU_DESCRIPTOR_HANDLE rtv1{rtv0.ptr + rtv_stride}, rtv2{rtv1.ptr + rtv_stride}; + const D3D12_CPU_DESCRIPTOR_HANDLE rtv1{rtv0.ptr + rtv_stride}, rtv2{rtv1.ptr + rtv_stride}, + rtv_ms{rtv2.ptr + rtv_stride}; const D3D12_CPU_DESCRIPTOR_HANDLE dsv1{dsv0.ptr + device->GetDescriptorHandleIncrementSize(dsv_heap_desc.Type)}; D3D12_RENDER_TARGET_VIEW_DESC rtv{}; rtv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; @@ -3097,6 +3101,10 @@ bool mesh57_target_capture(ID3D12Device* device, ID3D12Device* guest, IUnknown* guest->CreateRenderTargetView(color.Get(), &rtv, rtv1); rtv.Format = DXGI_FORMAT_R8G8B8A8_UINT; guest->CreateRenderTargetView(color.Get(), &rtv, rtv2); + D3D12_RENDER_TARGET_VIEW_DESC rtv_ms_desc{}; + rtv_ms_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rtv_ms_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS; + guest->CreateRenderTargetView(color_ms.Get(), &rtv_ms_desc, rtv_ms); D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; dsv.Format = DXGI_FORMAT_D16_UNORM; dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; @@ -3110,10 +3118,14 @@ bool mesh57_target_capture(ID3D12Device* device, ID3D12Device* guest, IUnknown* using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); using Close = HRESULT (WINAPI*)(IUnknown*); PlacedBuffer arguments(device, guest, sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), D3D12_RESOURCE_FLAG_NONE); + const auto observe_many = [&](IUnknown* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* color_views, + const D3D12_CPU_DESCRIPTOR_HANDLE* depth_view) { + slot(list, 50)(list, count, color_views, FALSE, depth_view); + slot(list, 61)(list, signature, 1, arguments.wrapped.Get(), 0, nullptr, 0); + }; const auto observe = [&](IUnknown* list, D3D12_CPU_DESCRIPTOR_HANDLE color_view, const D3D12_CPU_DESCRIPTOR_HANDLE* depth_view) { - slot(list, 50)(list, 1, &color_view, FALSE, depth_view); - slot(list, 61)(list, signature, 1, arguments.wrapped.Get(), 0, nullptr, 0); + observe_many(list, 1, &color_view, depth_view); }; const auto compare = [&](const std::string& expected) { check(x2w_d3d12_fixture_wait_mesh57_targets(5000) ? S_OK : E_FAIL, "wait for slot 57 target sidecar"); @@ -3153,6 +3165,20 @@ bool mesh57_target_capture(ID3D12Device* device, ID3D12Device* guest, IUnknown* if (!compare(first)) return false; observe(list.Get(), rtv1, &dsv0); if (!compare(first + second)) return false; + // Unresolved depth handle and sample-count mismatch must not record a tuple. + const D3D12_CPU_DESCRIPTOR_HANDLE unresolved_dsv{0}; + observe(list.Get(), rtv2, &unresolved_dsv); + observe(list.Get(), rtv_ms, &dsv0); + if (!compare(first + second)) return false; + // A derived slot-55 pipeline must not supply attachment tuples for the base slot-57 variant. + using CreateDerived = HRESULT (WINAPI*)(IUnknown*, void*, UINT, const void*, const GUID*, void**); + ComPtr derived; + check(slot(guest, 55)(guest, pipeline, 0, nullptr, &__uuidof(ID3D12PipelineState), + reinterpret_cast(derived.GetAddressOf())), + "create derived slot 55 pipeline"); + slot(list.Get(), 25)(list.Get(), derived.Get()); + observe(list.Get(), rtv2, &dsv1); + if (!compare(first + second)) return false; check(slot(list.Get(), 9)(list.Get()), "close first slot 57 target list"); check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&next_allocator)), @@ -3163,6 +3189,10 @@ bool mesh57_target_capture(ID3D12Device* device, ID3D12Device* guest, IUnknown* observe(next.Get(), rtv1, &dsv1); auto expected = first + second + read_only; if (!compare(expected)) return false; + const D3D12_CPU_DESCRIPTOR_HANDLE pair_rtvs[]{rtv1, rtv0}; + observe_many(next.Get(), 2, pair_rtvs, nullptr); + expected += "targets 2 29 28 dsv 0 writable 0 samples 1 0\n"; + if (!compare(expected)) return false; const struct { D3D12_CPU_DESCRIPTOR_HANDLE color; const D3D12_CPU_DESCRIPTOR_HANDLE* depth; @@ -3170,7 +3200,6 @@ bool mesh57_target_capture(ID3D12Device* device, ID3D12Device* guest, IUnknown* } remaining[]{ {rtv0, &dsv0, "targets 1 28 dsv 55 writable 1 samples 1 0\n"}, {rtv0, &dsv1, "targets 1 28 dsv 55 writable 0 samples 1 0\n"}, - {rtv1, nullptr, "targets 1 29 dsv 0 writable 0 samples 1 0\n"}, {rtv2, nullptr, "targets 1 30 dsv 0 writable 0 samples 1 0\n"}, {rtv2, &dsv0, "targets 1 30 dsv 55 writable 1 samples 1 0\n"}, }; From 8dde5cb1ffd9041f29d61647e842d8218cfd2d33 Mon Sep 17 00:00:00 2001 From: R0D4X Date: Tue, 1 Dec 2026 18:00:56 +0100 Subject: [PATCH 3/3] tests: verify .t57 sidecar on real fixed mesh57 pipeline fixtures --- tests/startup_indirect_draw_indexed.cpp | 31 ++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 70a6b72394..04a7ff327a 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -3049,14 +3049,39 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, append(expected_b.data(), sizeof(expected_b)); auto valid = expected; std::fill_n(valid.begin() + sizeof(key) + sizeof(sizes) + 15 * sizeof(UINT64), sizeof(UINT64), 0); + std::string expected_tuple = "targets " + std::to_string(profile.targets.NumRenderTargets); + for (UINT i = 0; i < profile.targets.NumRenderTargets; ++i) + expected_tuple += " " + std::to_string(static_cast(profile.targets.RTFormats[i])); + const bool depth_writable = profile.depth_format != DXGI_FORMAT_UNKNOWN && + profile.depth.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ZERO; + expected_tuple += " dsv " + std::to_string(static_cast(profile.depth_format)) + + " writable " + std::to_string(depth_writable ? 1 : 0) + " samples 1 0\n"; bool saw_valid = false, saw_other = false; for (const auto& f : std::filesystem::directory_iterator(cache)) if (f.path().extension() == ".s57") { std::ifstream in(f.path(), std::ios::binary); const std::vector persisted(std::istreambuf_iterator(in), {}); - if (persisted == valid && !saw_valid) saw_valid = true; - else if (persisted == expected && !saw_other) saw_other = true; - else return 1; + auto sidecar = f.path(); + sidecar.replace_extension(".t57"); + std::ifstream tin(sidecar, std::ios::binary); + const std::string observed((std::istreambuf_iterator(tin)), {}); + if (persisted == valid && !saw_valid) { + saw_valid = true; + if (observed.rfind(expected_tuple, 0) != 0) { + std::fprintf(stderr, "mesh57 real-pipeline sidecar mismatch:\nexpected prefix:\n%sactual:\n%s", + expected_tuple.c_str(), observed.c_str()); + return 1; + } + } else if (persisted == expected && !saw_other) { + saw_other = true; + if (observed != expected_tuple) { + std::fprintf(stderr, "mesh57 unreviewed sidecar mismatch:\nexpected:\n%sactual:\n%s", + expected_tuple.c_str(), observed.c_str()); + return 1; + } + } else { + return 1; + } } std::printf("fixed mesh state archives matching creation bytes: accepted=%d refused=%d\n", saw_valid, saw_other); if (!saw_valid || !saw_other) return 1;