diff --git a/CMakeLists.txt b/CMakeLists.txt index 5b2889d414..dd338d850a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1734,11 +1734,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/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index dcb0755f22..efde36abdc 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -19,6 +19,12 @@ The three fixture variants use one color target, six color targets with depth/st The ten tests above passed on the working tree based on `671b9ac`, Windows build 26200, with the debug layer enabled on WARP and an NVIDIA GeForce RTX 4060 Laptop GPU (driver 32.0.16.1656). +## Mesh-only depth + +A reviewed mesh-only profile specifies zero color targets, enabled depth writes and a typed DSV format. The creation descriptor has a zero PS pointer and length, and the exact PS span in the profile is empty. Versions 2–5 use a zeroed pixel entry and retain their MS layout and bindings. + +`native_fixed_mesh57_depth_only_hardware` checks all eight D32 depth texels after slot 61 execution. The WARP fixture checks the physical-adapter refusal, which follows the slot-86 mesh-only guard for a known WARP device removal. Both fixtures check missing and changed profiles, a color target, a zero depth-write mask and a typeless DSV. + ## Per-pixel texture selection The `native_fixed_mesh57_waterfall_{warp,hardware}` fixture draws a triangle covering eight pixels. The guest PS uses READFIRSTLANE, CMPX, an indexed descriptor load, IMAGE_SAMPLE and a WREXEC retry. Neighboring pixels select different Texture2D views. With a unit UV gradient the two views return red and green from mip 1. The `waterfall_fine` variant holds UV constant and both views return blue from mip 0. The shader computes quad derivatives before sampling the per-pixel texture. Both gradient cases passed on WARP and the RTX 4060 Laptop with the debug layer enabled. Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_(pixel_heap|waterfall(_fine)?)_(warp|hardware)$'` to reproduce. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 040ae3e4b2..9465fbcf6a 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1749,6 +1749,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_PIPELINE_COLOUR=1` | diagnostic only, debug switch, in render mode: a `DrawInstanced`, `DrawIndexedInstanced` or `ExecuteIndirect` draw that draws nothing gets one flat marker tile in render target 0, in a colour taken from its pipeline key, and logs `x2w-draw colour #rrggbb for ` once per key ([details](experiments/pipeline-colour-fallback.md)). Not a fallback: the refused draw still draws nothing, and the tiles can tint later passes. Unset, nothing is drawn or logged | | `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 native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`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. Manifests and every other cache file are still looked up on disk. | | `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_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 bb75a9b805..ce6a2ff625 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 60e9987213..e6e385595c 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, listed at the first cache_lookup (src/startup_stubs/cache_index.h). @@ -452,6 +452,19 @@ 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) +{ + 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); + return !move_flags && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; +} + // 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) { @@ -461,14 +474,7 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: if (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)) return true; - DeleteFileW(temporary); - return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; + return publish_request_file(path, temporary, data, bytes, 0); } bool native_shaders_only() @@ -894,39 +900,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); @@ -938,7 +1093,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; @@ -953,6 +1110,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 2a92ec33b0..e5b4cd8fbf 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -106,6 +106,7 @@ #include #include #include +#include #include #include #include @@ -280,7 +281,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) @@ -2946,6 +2949,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 @@ -3795,11 +3800,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. @@ -3818,16 +3825,21 @@ 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.root != pass.graphics_root) || 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); @@ -4518,6 +4530,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. @@ -6756,6 +6769,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 @@ -7313,9 +7337,14 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, } } note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); + if constexpr (N == 57) { #ifdef X2W_NATIVE_SHADERS - if constexpr (N == 57) if (render_mode()) prepare_native_mesh57(static_cast(*out)); + if (render_mode()) + prepare_native_mesh57(static_cast(*out)); + else #endif + note_mesh57_outcome(Mesh57Outcome::disabled); + } return S_OK; } @@ -7856,6 +7885,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled, compute_builder_gate_refusals, compute_inputs_gpu_copied, compute_inputs_snapshot, compute_inputs_snapshot_kib); log_compute_census(); + char mesh57_line[1536]; + mesh57_outcome_line(mesh57_line); + log("%s", mesh57_line); } if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index 0c2fe5b3ef..1d4a521b9d 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -50,7 +50,8 @@ struct Mesh86Request { std::vector ms, ps, stream; }; -bool mesh86_hardware_depth() +// A mesh-only depth fixture removed the device on WARP. Both mesh paths use this guard. +bool mesh_hardware_depth() { x2w_startup::ComPtr factory; x2w_startup::ComPtr adapter; @@ -244,7 +245,7 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d std::snprintf(why, why_size, "slot86 mesh request %016llx: cache key, stage or bytecode mismatch", key); return nullptr; } - if (!ps && !mesh86_hardware_depth()) { + if (!ps && !mesh_hardware_depth()) { std::snprintf(why, why_size, "slot86 mesh request %016llx: depth-only requires a physical adapter", key); return nullptr; } diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 8acc02e78f..b6aeb070c8 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -218,51 +218,125 @@ extern "C" __declspec(dllexport) void x2w_d3d12_mesh57_profile_stats(LONG* looku if (opens) *opens = mesh57_profile_opens; } +enum class Mesh57Outcome { + disabled, ps_absent, unsupported_stage_or_descriptor, missing_creation_root_or_state, + profile_absent, profile_open_failed, profile_header, profile_pixel_entry, profile_version, + profile_constants, profile_root_mapping, profile_view_count, profile_view_entries, + profile_view_mapping, profile_heap_mapping, profile_input_length, profile_input_content, + profile_trailing_bytes, profile_attachment_state, profile_creation_root, profile_exception, + lowering_reached, lowering_refused, pipeline_refused, ready, count +}; + +volatile LONG64 mesh57_outcomes[static_cast(Mesh57Outcome::count)]; + +void note_mesh57_outcome(Mesh57Outcome outcome) +{ + InterlockedIncrement64(&mesh57_outcomes[static_cast(outcome)]); +} + +void mesh57_outcome_line(char (&line)[1536]) +{ + static constexpr const char* names[]{ + "disabled", "ps_absent", "unsupported_stage_or_descriptor", "missing_creation_root_or_state", + "profile_absent", "profile_open_failed", "profile_rejected_header", "profile_rejected_pixel_entry", + "profile_rejected_version", "profile_rejected_constants", "profile_rejected_root_mapping", + "profile_rejected_view_count", "profile_rejected_view_entries", "profile_rejected_view_mapping", + "profile_rejected_heap_mapping", "profile_rejected_input_length", "profile_rejected_input_content", + "profile_rejected_trailing_bytes", "profile_rejected_attachment_state", "profile_rejected_creation_root", + "profile_rejected_exception", "lowering_reached", "lowering_refused", "pipeline_refused", "ready" + }; + static_assert(std::size(names) == std::size(mesh57_outcomes)); + constexpr char prefix[] = "x2w-render native slot57 preparation:"; + std::memcpy(line, prefix, sizeof(prefix)); + int used = sizeof(prefix) - 1; + for (int i = 0; i < static_cast(Mesh57Outcome::count); ++i) { + const auto count = InterlockedCompareExchange64(&mesh57_outcomes[i], 0, 0); + const int remaining = static_cast(sizeof(line)) - used; + const int n = std::snprintf(line + used, remaining, " %s %lld", names[i], static_cast(count)); + if (n < 0 || n >= remaining) + return; + used += n; + } +} + #ifdef X2W_NATIVE_SHADERS void prepare_native_mesh57(Wrapper* pipeline) { wchar_t sdk[MAX_PATH], path[MAX_PATH]; const DWORD sdk_length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); if (!sdk_length || sdk_length >= MAX_PATH) - return; + return note_mesh57_outcome(Mesh57Outcome::disabled); const auto* info = pipeline_info(pipeline); - if (!info || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) - return; - const auto& ms_bytes = *info->fixed_ms; - const auto& ps_bytes = *info->fixed_ps; + const auto refuse = [](const char* reason) { + static LONG refusals; + if (first_calls(refusals, 12)) log("x2w-render native slot57 mesh refused: %s", reason); + }; + if (!info || info->desc.size() != 0x300) { + refuse("unsupported fixed descriptor"); + return note_mesh57_outcome(Mesh57Outcome::unsupported_stage_or_descriptor); + } u64 fields[0x300 / sizeof(u64)]; std::memcpy(fields, info->desc.data(), sizeof(fields)); + const bool depth_only = !fields[5] && !fields[6]; + if (!info->fixed_ms || (!depth_only && !info->fixed_ps)) { + refuse("unsupported or uncaptured shader stages"); + // A nonzero PS pointer without any PS bytes fails capture and cannot use the depth-only path. + if (fields[5] && !fields[6]) + return note_mesh57_outcome(Mesh57Outcome::ps_absent); + return note_mesh57_outcome(Mesh57Outcome::unsupported_stage_or_descriptor); + } + const auto& ms_bytes = *info->fixed_ms; + const std::vector empty; + const auto& ps_bytes = depth_only ? empty : *info->fixed_ps; auto* root = as_wrapper(reinterpret_cast(fields[0])); if (!root || root->own().kind != root_signature_kind || !root->own().real || !root_info(root) || - fields[2] != info->state_a.size() || fields[4] != info->state_b.size()) - return; + fields[2] != info->state_a.size() || fields[4] != info->state_b.size()) { + if (depth_only) refuse("missing depth-only creation root or fixed state"); + return note_mesh57_outcome(Mesh57Outcome::missing_creation_root_or_state); + } std::vector root_blob; { x2w_startup::ExclusiveNoteLock guard(note_lock); const auto it = root_blobs().find(root); - if (it == root_blobs().end()) - return; + if (it == root_blobs().end()) { + if (depth_only) refuse("missing depth-only creation root blob"); + return note_mesh57_outcome(Mesh57Outcome::missing_creation_root_or_state); + } root_blob = it->second; } constexpr char revision[] = "x2w-startup-mesh-57-3"; const u64 key = fnv_part(root_blob, fnv_part(ps_bytes, fnv_part(ms_bytes, fnv_bytes(revision, sizeof(revision) - 1)))); const auto normalized = x2w_startup::normalize_mesh57_descriptor(info->desc); const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(normalized, key))); - if (!cache_path(path, L"", variant, L".mesh57-state")) - return; + if (!cache_path(path, L"", variant, L".mesh57-state")) { + if (depth_only) refuse("depth-only profile cache unavailable"); + return note_mesh57_outcome(Mesh57Outcome::profile_absent); + } InterlockedIncrement(&mesh57_profile_lookups); // Profiles are placed before the process starts and most creations have none: skip the open when the // cache listing has no such name. A profile written while the process runs is read by the next one. - if (cache_lookup(L"", variant, L".mesh57-state") == x2w_startup::CacheLookup::absent) - return; + if (cache_lookup(L"", variant, L".mesh57-state") == x2w_startup::CacheLookup::absent) { + if (depth_only) { + static LONG missing; + if (first_calls(missing, 12)) log("x2w-render native slot57 mesh %016llx refused: depth-only profile absent", key); + } + return note_mesh57_outcome(Mesh57Outcome::profile_absent); + } InterlockedIncrement(&mesh57_profile_opens); std::ifstream file(std::filesystem::path(path), std::ios::binary); - if (!file) - return; + if (!file) { + if (depth_only) refuse("depth-only profile could not be opened"); + return note_mesh57_outcome(Mesh57Outcome::profile_open_failed); + } + auto refusal = Mesh57Outcome::profile_exception; + const auto profile_error = [&](Mesh57Outcome reason, const auto& message) { + refusal = reason; + return std::runtime_error(message); + }; try { x2w_startup::Mesh57Profile profile{}; if (!file.read(reinterpret_cast(&profile), sizeof(profile))) - throw std::runtime_error("invalid profile header"); + throw profile_error(Mesh57Outcome::profile_header, "invalid profile header"); const bool pixel_heap = !std::memcmp(profile.magic,"X2WM576",8); const bool direct_heap = pixel_heap || !std::memcmp(profile.magic, "X2WM575", 8); const bool buffers = direct_heap || !std::memcmp(profile.magic, "X2WM574", 8); @@ -271,43 +345,44 @@ void prepare_native_mesh57(Wrapper* pipeline) x2w_startup::Mesh57PixelEntry entry{}; if (varying_pixel) { if (!file.read(reinterpret_cast(&entry), sizeof(entry))) - throw std::runtime_error("truncated fixed pixel entry"); + throw profile_error(Mesh57Outcome::profile_pixel_entry, "truncated fixed pixel entry"); } else if (std::memcmp(profile.magic, "X2WM571", 8)) { - throw std::runtime_error("unknown fixed profile version"); + throw profile_error(Mesh57Outcome::profile_version, "unknown fixed profile version"); } + if (depth_only && (pixel_heap || entry.enable || entry.address || entry.wave_size)) + throw profile_error(Mesh57Outcome::profile_pixel_entry, "depth-only profile contains pixel entry metadata"); x2w_startup::Mesh57ConstantEntry mapping{}; if (mapped) { if (!file.read(reinterpret_cast(&mapping), sizeof(mapping)) || mapping.root_parameter >= 16 || !mapping.count || mapping.count > 8 || !root_heap_flags(root)) - throw std::runtime_error("invalid MS constant mapping or guest root is not deferred"); + throw profile_error(Mesh57Outcome::profile_constants, "invalid MS constant mapping or guest root is not deferred"); } else if (!root_info(root)->empty() || root_heap_flags(root)) { - throw std::runtime_error("fixed mesh profile lacks guest root mapping"); + throw profile_error(Mesh57Outcome::profile_root_mapping, "fixed mesh profile lacks guest root mapping"); } std::vector view_entries; if (buffers) { UINT count{}; if (!file.read(reinterpret_cast(&count), sizeof(count)) || !count || count > 15) - throw std::runtime_error("invalid MS view entry count"); + throw profile_error(Mesh57Outcome::profile_view_count, "invalid MS view entry count"); view_entries.resize(count); if (!file.read(reinterpret_cast(view_entries.data()), count * sizeof(view_entries[0]))) - throw std::runtime_error("truncated MS view mappings"); + throw profile_error(Mesh57Outcome::profile_view_entries, "truncated MS view mappings"); for (const auto& e : view_entries) - if (e.root_address > 1) throw std::runtime_error("invalid MS view mapping"); + if (e.root_address > 1) throw profile_error(Mesh57Outcome::profile_view_mapping, "invalid MS view mapping"); } UINT heap_sgpr{}; if (direct_heap && (!file.read(reinterpret_cast(&heap_sgpr), sizeof(heap_sgpr)) || !(root_heap_flags(root) & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED))) - throw std::runtime_error("missing MS resource heap mapping"); + throw profile_error(Mesh57Outcome::profile_heap_mapping, "missing MS resource heap mapping"); const auto match = [&](UINT part, const char* name, const void* bytes, size_t size) { if (size != profile.lengths[part]) - throw std::runtime_error(std::string("profile input bytes differ: ") + name + - " length " + std::to_string(profile.lengths[part]) + - " != " + std::to_string(size)); + throw profile_error(Mesh57Outcome::profile_input_length, std::string("profile input bytes differ: ") + name + + " length " + std::to_string(profile.lengths[part]) + " != " + std::to_string(size)); if (!size) return; std::string copy(size, 0); if (!file.read(copy.data(), size) || std::memcmp(copy.data(), bytes, size)) - throw std::runtime_error(std::string("profile input bytes differ: ") + name + " content"); + throw profile_error(Mesh57Outcome::profile_input_content, std::string("profile input bytes differ: ") + name + " content"); }; match(0, "normalized descriptor", normalized.data(), normalized.size()); match(1, "state_a", info->state_a.data(), info->state_a.size()); @@ -316,13 +391,25 @@ void prepare_native_mesh57(Wrapper* pipeline) match(4, "mesh shader", ms_bytes.data(), ms_bytes.size()); match(5, "pixel shader", ps_bytes.data(), ps_bytes.size()); if (file.peek() != EOF) - throw std::runtime_error("profile input bytes differ: trailing bytes after the pixel shader"); - if (!profile.targets.NumRenderTargets || profile.targets.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT || + throw profile_error(Mesh57Outcome::profile_trailing_bytes, "profile input bytes differ: trailing bytes after the pixel shader"); + if (depth_only) { + if (profile.targets.NumRenderTargets) + throw profile_error(Mesh57Outcome::profile_attachment_state, "depth-only profile has color targets"); + if (!profile.depth.DepthEnable || profile.depth.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ALL) + throw profile_error(Mesh57Outcome::profile_attachment_state, "depth-only profile requires enabled depth writes"); + const auto format = profile.depth_format; + if (format != DXGI_FORMAT_D16_UNORM && format != DXGI_FORMAT_D32_FLOAT && + format != DXGI_FORMAT_D24_UNORM_S8_UINT && format != DXGI_FORMAT_D32_FLOAT_S8X24_UINT) + throw profile_error(Mesh57Outcome::profile_attachment_state, "depth-only profile requires a typed DSV format"); + } + if ((!depth_only && !profile.targets.NumRenderTargets) || profile.targets.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT || ((profile.depth.DepthEnable || profile.depth.StencilEnable) && profile.depth_format == DXGI_FORMAT_UNKNOWN) || profile.samples.Count != 1 || profile.samples.Quality || profile.sample_mask != UINT_MAX || (profile.wave_size != 32 && profile.wave_size != 64)) - throw std::runtime_error("unsupported fixed attachment or sample state"); + throw profile_error(Mesh57Outcome::profile_attachment_state, "unsupported fixed attachment or sample state"); + if (depth_only && !mesh_hardware_depth()) + throw profile_error(Mesh57Outcome::pipeline_refused, "depth-only mesh requires a physical adapter"); const std::string ms(ms_bytes.begin(), ms_bytes.end()), ps(ps_bytes.begin(), ps_bytes.end()); x2w::MeshStageLayout mesh_layout{profile.threads, profile.vertices, profile.primitives, profile.topology, profile.group_stride, profile.wave_size == 32}; @@ -336,11 +423,14 @@ void prepare_native_mesh57(Wrapper* pipeline) if (mapped) { if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(root_blob.data(), root_blob.size(), IID_PPV_ARGS(&deserializer))) || FAILED(deserializer->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &guest_desc))) - throw std::runtime_error("invalid MS creation root signature"); + throw profile_error(Mesh57Outcome::profile_creation_root, "invalid MS creation root signature"); mesh_layout.root_inputs.push_back({mapping.sgpr, mapping.root_parameter, mapping.count}); for (const auto& e : view_entries) mesh_layout.root_inputs.push_back({e.sgpr, e.root_parameter, 0, e.root_address != 0}); } + // This milestone overlaps the terminal counts below. + note_mesh57_outcome(Mesh57Outcome::lowering_reached); + refusal = Mesh57Outcome::lowering_refused; auto native = mapped ? x2w::translate_mesh_program(ms, mesh_layout, guest_desc->Desc_1_1) : x2w::translate_mesh_program(ms, mesh_layout); const bool mapped_constants = mapped && native.constants.size() == 1 && @@ -387,7 +477,7 @@ void prepare_native_mesh57(Wrapper* pipeline) std::string ps_ir; std::vector spans; std::vector samplers; - if (varying_pixel) { + if (!depth_only && varying_pixel) { auto pixel = x2w::translate_mesh_pixel_program(ps, entry.enable, entry.address, entry.wave_size, pixel_heap ? &guest_desc->Desc_1_1 : nullptr); if (pixel_heap) { if (pixel.pixel_heap_spans.empty()) throw std::runtime_error("missing PS texture heap reads"); @@ -402,18 +492,20 @@ void prepare_native_mesh57(Wrapper* pipeline) throw std::runtime_error("PS needs root or heap bindings"); x2w::validate_raster_link(native, pixel); ps_ir = std::move(pixel.dxil_ir); - } else { + } else if (!depth_only) { ps_ir = x2w::direct_gfx1013_constant_pixel(ps); } + refusal = Mesh57Outcome::pipeline_refused; auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); const auto cache = std::filesystem::path(path).parent_path(); const auto ms_output = compiler.compile(native.dxil_ir, L"ms_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); - const auto ps_output = - compiler.compile(ps_ir, L"ps_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); + x2w::CompiledShader ps_output; + if (!depth_only) + ps_output = compiler.compile(ps_ir, L"ps_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); x2w::meshlet::MeshOnlyPipelineStream stream{}; stream.root_signature.value = reinterpret_cast(root); stream.ms.value = {ms_output.dxil.data(), ms_output.dxil.size()}; - stream.ps.value = {ps_output.dxil.data(), ps_output.dxil.size()}; + if (!depth_only) stream.ps.value = {ps_output.dxil.data(), ps_output.dxil.size()}; stream.blend.value = profile.blend; stream.sample_mask.value = profile.sample_mask; stream.rasterizer.value = profile.rasterizer; @@ -461,8 +553,10 @@ void prepare_native_mesh57(Wrapper* pipeline) info->mesh57_reads = std::move(reads); info->mesh57_heap_word = heap_word; } + note_mesh57_outcome(Mesh57Outcome::ready); log("x2w-render native slot57 mesh %016llx ready", key); } catch (const std::exception& e) { + note_mesh57_outcome(refusal); log("x2w-render native slot57 mesh %016llx refused: %s", key, e.what()); } } diff --git a/tests/cmake/native_mesh57_depth_only.cmake b/tests/cmake/native_mesh57_depth_only.cmake new file mode 100644 index 0000000000..dcc4b9c8ca --- /dev/null +++ b/tests/cmake/native_mesh57_depth_only.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(backend warp hardware) + add_test(NAME native_fixed_mesh57_depth_only_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_depth_only_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_DEPTH_ONLY=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + endforeach() +endif() diff --git a/tests/cmake/native_mesh57_outcomes.cmake b/tests/cmake/native_mesh57_outcomes.cmake new file mode 100644 index 0000000000..13cfda7c22 --- /dev/null +++ b/tests/cmake/native_mesh57_outcomes.cmake @@ -0,0 +1,8 @@ +if(TARGET compile_dxil AND TARGET startup_indirect_draw_indexed + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_mesh57_outcomes_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_mesh57_outcomes_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_OUTCOMES=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + endforeach() +endif() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 2385d8484b..901d14d012 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -34,6 +34,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" { @@ -937,8 +938,9 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{heap_kind, target_count, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; ComPtr heap; - check((cached_depth_only ? guest : device)->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), - "create attachment heap"); + if (target_count) + check((cached_depth_only ? guest : device)->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), + "create attachment heap"); std::vector rtvs; D3D12_CPU_DESCRIPTOR_HANDLE native_dsv{}; D3D12_CPU_DESCRIPTOR_HANDLE rtv{}; @@ -946,7 +948,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ using GetCpu = UINT64(WINAPI*)(IUnknown*, void*); rtv.ptr = slot(heap.Get(), 9)(heap.Get(), nullptr); native_dsv = native_object(device, guest, heap.Get())->GetCPUDescriptorHandleForHeapStart(); - } else { + } else if (heap) { rtv = heap->GetCPUDescriptorHandleForHeapStart(); } for (UINT i = 0; i < target_count; ++i) { @@ -964,6 +966,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ rtv.ptr += device->GetDescriptorHandleIncrementSize(heap_kind); } ComPtr fixed_depth; + const bool fixed_stencil = fixed_profile && fixed_profile->depth_format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT; ComPtr fixed_depth_heap; D3D12_CPU_DESCRIPTOR_HANDLE fixed_dsv{}, desktop_fixed_dsv{}; if (fixed_profile && fixed_profile->depth_format != DXGI_FORMAT_UNKNOWN) { @@ -972,7 +975,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; D3D12_CLEAR_VALUE initial_depth{}; initial_depth.Format = desc.Format; - initial_depth.DepthStencil = {0.25f, 3}; + initial_depth.DepthStencil = {0.25f, static_cast(fixed_stencil ? 3 : 0)}; fixed_depth = resource(device, desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &initial_depth); const D3D12_DESCRIPTOR_HEAP_DESC descriptors{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; check(guest->CreateDescriptorHeap(&descriptors,IID_PPV_ARGS(&fixed_depth_heap)), "create fixture DSV heap"); @@ -1103,9 +1106,12 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ const UINT bound_targets = target_count - (refusal == Refusal::mesh_attachment_count ? 1 : 0); slot(wrapped, 50)(wrapped, bound_targets, rtvs.data(), FALSE, fixed_depth ? &fixed_dsv : nullptr); if (fixed_depth) { - list->ClearDepthStencilView(desktop_fixed_dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.25f, 3, 0, nullptr); - using StencilRef = void(WINAPI*)(IUnknown*,UINT); - slot(wrapped,24)(wrapped,7); + const auto flags = fixed_stencil ? D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL : D3D12_CLEAR_FLAG_DEPTH; + list->ClearDepthStencilView(desktop_fixed_dsv, flags, 0.25f, fixed_stencil ? 3 : 0, 0, nullptr); + if (fixed_stencil) { + using StencilRef = void(WINAPI*)(IUnknown*,UINT); + slot(wrapped,24)(wrapped,7); + } } } std::vector> fixed_textures; @@ -1436,14 +1442,15 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ } } if (fixed_depth) { + const UINT plane_count = fixed_stencil ? 2 : 1; const auto desc = fixed_depth->GetDesc(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT planes[2]{}; UINT64 row_sizes[2]{}; - device->GetCopyableFootprints(&desc, 0, 2, 0, planes, nullptr, row_sizes, &bytes); + device->GetCopyableFootprints(&desc, 0, plane_count, 0, planes, nullptr, row_sizes, &bytes); const auto rb = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); ComputeCommands copy(device, kept_direct_queue(device), nullptr); transition(copy.list.Get(), fixed_depth.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); - for (UINT plane=0; plane<2; ++plane) { + for (UINT plane=0; planeUnmap(0,&untouched); if (!match) return false; - std::printf("%s: 8 depth/stencil texels matched, selected pixel %.2f/%u\n", - label,fixed_mesh_pixels==1?0.5:0.25,fixed_mesh_pixels==1?7:3); + std::printf("%s: 8 texels matched across %u planes, selected depth %.2f\n", + label, plane_count, fixed_mesh_pixels==1 ? 0.5 : 0.25); } return true; } @@ -1496,7 +1503,7 @@ void refuse_each_reason(ID3D12Device* guest, ID3D12CommandSignature* draw_indexe } // 300 empty console presents (queue slot 32) reach the render-totals heartbeat; nothing is shown. -std::string indirect_line(ID3D12Device* guest, const std::wstring& log_path) +std::string render_totals_line(ID3D12Device* guest, const std::wstring& log_path, const char* prefix) { const D3D12_COMMAND_QUEUE_DESC desc{}; ComPtr queue; @@ -1509,7 +1516,7 @@ std::string indirect_line(ID3D12Device* guest, const std::wstring& log_path) std::ifstream file(log_path, std::ios::binary); std::string line, found; while (std::getline(file, line)) - if (line.rfind("x2w-render indirect:", 0) == 0) found = line; + if (line.rfind(prefix, 0) == 0) found = line; while (!found.empty() && (found.back() == '\r' || found.back() == '\n')) found.pop_back(); return found; } @@ -2054,8 +2061,10 @@ bool fixed_mesh_create_contract(ID3D12Device* guest) } // namespace static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, - const std::wstring& log_path) + const std::wstring& log_path, bool warp) { + const bool depth_only = GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_DEPTH_ONLY", nullptr, 0) != 0; + const bool outcomes = GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_OUTCOMES", nullptr, 0) != 0; const bool mrt = GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_MRT", nullptr, 0) != 0; const bool waterfall=GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_WATERFALL",nullptr,0)!=0; const bool pixel_heap=waterfall || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_PIXEL_HEAP",nullptr,0)!=0; @@ -2155,6 +2164,7 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, 0xf0800f08,0x00e50005,0xbeb43a34,0xbf85fff7,0xbefe043c, 0xf800180f,0x03020100,0xbf810000}; } + if (depth_only) ps.clear(); const auto ms_size = ms.size()*sizeof(UINT), ps_size = ps.size()*sizeof(UINT); const std::array expected_a{0x12345678, 0x9abcdef0}; const bool masked = GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_MASK", nullptr, 0) != 0; @@ -2231,13 +2241,21 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, profile.depth.FrontFace = profile.depth.BackFace = { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_REPLACE, D3D12_COMPARISON_FUNC_ALWAYS}; } + if (depth_only) { + profile.targets = {}; + profile.depth = {}; + profile.depth.DepthEnable = TRUE; + profile.depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + profile.depth.DepthFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; + profile.depth_format = DXGI_FORMAT_D32_FLOAT; + } { std::ofstream out(cache / name, std::ios::binary); const auto put = [&](const void* data, size_t n) { out.write(static_cast(data), n); }; put(&profile, sizeof(profile)); if (varying) { const UINT position_x = (compare_vcc || waterfall) ? 1u<<8 : 0; - const x2w_startup::Mesh57PixelEntry entry{position_x,position_x,64}; + const x2w_startup::Mesh57PixelEntry entry{position_x,position_x,depth_only ? 0u : 64u}; put(&entry,sizeof(entry)); if (constants) { const x2w_startup::Mesh57ConstantEntry mapping{12,4,1}; @@ -2256,7 +2274,7 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, put(state_b.data(), sizeof(state_b)); put(blob->GetBufferPointer(), blob->GetBufferSize()); put(ms.data(), ms_size); - put(ps.data(), ps_size); + if (ps_size) put(ps.data(), ps_size); if (!out) return 1; } @@ -2268,7 +2286,7 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, fields[0] = reinterpret_cast(root.Get()); fields[1] = reinterpret_cast(state_a.data()); fields[3] = reinterpret_cast(state_b.data()); - fields[5] = reinterpret_cast(ps.data()); + fields[5] = ps_size ? reinterpret_cast(ps.data()) : 0; fields[13] = reinterpret_cast(ms.data()); const auto create = [&] { ComPtr pso; @@ -2278,35 +2296,85 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, "create native fixed mesh"); return pso; }; + const auto log_file = std::filesystem::path(log_path); + const auto has_native_pso = [&](IUnknown* candidate) { + return bool(native_object(device, guest, candidate, true)); + }; + const auto logged_refusal = [&](std::uintmax_t offset, const char* reason) { + char expected[180]; + std::snprintf(expected, sizeof(expected), "x2w-render native slot57 mesh %016llx refused: %s", key, reason); + std::ifstream log(log_file, std::ios::binary); + log.seekg(static_cast(offset)); + std::string line; + while (std::getline(log, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line == expected) return true; + } + std::fprintf(stderr, "fixed mesh profile: missing appended log line '%s'\n", expected); + return false; + }; + if (outcomes) { + // The mesh-only creation reaches the profile lookup with an empty PS span. + fields[5] = fields[6] = 0; + create(); + fields[5] = reinterpret_cast(ps.data()); + fields[6] = ps_size; + } const auto pso = create(); if (compare_vcc) std::printf("native fixed mesh compare mask: reviewed stage pair linked and created a color PSO\n"); fields[15] = 1; // Same stages and root, unreviewed fixed pipeline state. const auto mismatched = create(); - { - // native_mesh57.inl: throw std::runtime_error(std::string("profile input bytes differ: ") + name + " content"); - char expected[128]; - std::snprintf(expected, sizeof(expected), - "x2w-render native slot57 mesh %016llx refused: profile input bytes differ: normalized descriptor content", - key); - std::ifstream log{std::filesystem::path(log_path)}; - std::string line; - while (std::getline(log, line) && line != expected) {} - if (!log) { - std::fprintf(stderr, "unreviewed fixed mesh state: missing log line '%s'\n", expected); + if (!logged_refusal(0, "profile input bytes differ: normalized descriptor content")) return 1; + // Additional fixed states have no profile. Only the two profiles above may be opened. + const UINT extra_limit = depth_only ? 3 : 66; + const auto absent_profile_offset = std::filesystem::file_size(log_file); + for (UINT64 extra = 2; extra < extra_limit; ++extra) { + fields[15] = extra; + const auto missing = create(); + if (depth_only && (has_native_pso(missing.Get()) || !logged_refusal(absent_profile_offset, "depth-only profile absent"))) return 1; - } } - // 64 more fixed states without a profile. Only the two profiles above may be opened. - for (UINT64 extra = 2; extra < 66; ++extra) { - fields[15] = extra; - create(); + if (outcomes || depth_only) { + const auto expect_outcomes = [&](const char* label, int unsupported_count) { + const char* prefix = "x2w-render native slot57 preparation:"; + const auto line = render_totals_line(guest, log_path, prefix); + const auto expected = std::string(prefix) + + " disabled 0 ps_absent 0 unsupported_stage_or_descriptor " + std::to_string(unsupported_count) + + " missing_creation_root_or_state 0 profile_absent " + (depth_only ? "1" : "65") + + " profile_open_failed 0 profile_rejected_header 0 profile_rejected_pixel_entry 0" + " profile_rejected_version 0 profile_rejected_constants 0 profile_rejected_root_mapping 0" + " profile_rejected_view_count 0 profile_rejected_view_entries 0 profile_rejected_view_mapping 0" + " profile_rejected_heap_mapping 0 profile_rejected_input_length 0 profile_rejected_input_content 1" + " profile_rejected_trailing_bytes 0 profile_rejected_attachment_state 0 profile_rejected_creation_root 0" + " profile_rejected_exception 0" + + (depth_only && warp ? " lowering_reached 0 lowering_refused 0 pipeline_refused 1 ready 0" + : " lowering_reached 1 lowering_refused 0 pipeline_refused 0 ready 1"); + if (line == expected) return true; + std::fprintf(stderr, "%s: expected preparation totals:\n%s\nreceived:\n%s\n", + label, expected.c_str(), line.c_str()); + return false; + }; + if (depth_only) { + if (!expect_outcomes("depth-only creation", 0)) return 1; + } else { + fields[15] = 0; + const auto ps_pointer = fields[5]; + // Retain the PS length and the rest of the reviewed descriptor. + fields[5] = 0; + create(); + if (!expect_outcomes("null PS pointer with nonzero length", 1)) return 1; + fields[5] = 1; // Nonzero address in the unreadable low 64 KiB. + create(); + fields[5] = ps_pointer; + if (!expect_outcomes("uncaptured PS with nonzero pointer and length", 2)) return 1; + } } fields[15] = 1; LONG lookups = -1, opens = -1; x2w_d3d12_mesh57_profile_stats(&lookups, &opens); std::printf("native fixed mesh profile lookups %ld, opens %ld (2 profiles, 2000 other cache files)\n", lookups, opens); - if (lookups != 66 || opens != 2) + if (lookups != static_cast(extra_limit) + (outcomes ? 1 : 0) || opens != 2) return 1; // Reuse the indexed profile filename with the original descriptor after checking lookup counts. fields[15] = 0; @@ -2317,7 +2385,6 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, if (!file.read(original_profile.data(), original_profile.size())) return 1; } - const auto log_file = std::filesystem::path(log_path); const auto write_profile = [&](const char* data, size_t size) { std::ofstream file(profile_path, std::ios::binary | std::ios::trunc); file.write(data, size); @@ -2331,27 +2398,60 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, std::fprintf(stderr, "could not write malformed fixed mesh profile\n"); return false; } - create(); + const auto refused = create(); if (!write_profile(original_profile.data(), original_profile.size())) { std::fprintf(stderr, "could not restore original fixed mesh profile\n"); return false; } - char expected[160]; - std::snprintf(expected, sizeof(expected), - "x2w-render native slot57 mesh %016llx refused: %s", key, reason); - std::ifstream log(log_file, std::ios::binary); - log.seekg(static_cast(log_offset)); - std::string line; - while (std::getline(log, line)) { - if (!line.empty() && line.back() == '\r') - line.pop_back(); - if (line == expected) - return true; - } - std::fprintf(stderr, "malformed fixed mesh profile: missing appended log line '%s'\n", expected); - return false; + return logged_refusal(log_offset, reason) && (!depth_only || !has_native_pso(refused.Get())); }; + if (depth_only) { + if (has_native_pso(pso.Get()) == warp || has_native_pso(mismatched.Get())) { + std::fprintf(stderr, "depth-only fixture: unexpected native PSO availability\n"); + return 1; + } + const auto reject = [&](const x2w_startup::Mesh57Profile& state, const char* reason) { + auto input = original_profile; + std::memcpy(input.data(), &state, sizeof(state)); + return check_profile_refusal(input.data(), input.size(), reason); + }; + auto color = profile; + color.targets.NumRenderTargets = 1; + color.targets.RTFormats[0] = format; + auto read_only = profile; + read_only.depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + auto typeless = profile; + typeless.depth_format = DXGI_FORMAT_R32_TYPELESS; + if (!reject(color, "depth-only profile has color targets") || + !reject(read_only, "depth-only profile requires enabled depth writes") || + !reject(typeless, "depth-only profile requires a typed DSV format")) return 1; + // A nonzero pointer with zero PS length is malformed, even with a reviewed depth profile. + fields[5] = reinterpret_cast(ms.data()); + const auto malformed = create(); + fields[5] = 0; + if (has_native_pso(malformed.Get())) return 1; + if (warp) { + if (!logged_refusal(0, "depth-only mesh requires a physical adapter")) return 1; + } else { + D3D12_INDIRECT_ARGUMENT_DESC arg{}; + arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + D3D12_COMMAND_SIGNATURE_DESC desc{sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), 1, &arg, 0}; + ComPtr signature; + check(guest->CreateCommandSignature(&desc, nullptr, IID_PPV_ARGS(&signature)), "depth-only mesh signature"); + const auto work = writer_pipeline(device, writer, "write_one_mesh_group"); + const auto verify = [&](IUnknown* pipeline, bool draws, const char* label) { + return run(device, guest, writer, work.Get(), root.Get(), pipeline, signature.Get(), DrawKind::mesh, + false, draws ? Refusal::none : Refusal::mesh_pending, label, nullptr, false, nullptr, + false, false, 0, false, false, nullptr, nullptr, false, draws ? 1 : 2, &profile); + }; + if (!verify(pso.Get(), true, "depth-only native fixed mesh") || + !verify(mismatched.Get(), false, "depth-only fixed mesh with changed state")) return 1; + } + DeleteFileW(log_path.c_str()); + std::filesystem::remove_all(cache); + return 0; + } if (!check_profile_refusal(original_profile.data(), sizeof(profile) - 1, "invalid profile header")) return 1; const bool constants_only = constants && !buffers; @@ -2472,6 +2572,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)}; @@ -2503,6 +2604,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; @@ -2632,7 +2855,7 @@ int main(int argc, char** argv) try const D3D12_ROOT_SIGNATURE_DESC graphics_desc{0, nullptr, 0, nullptr, root_flags}; const auto writer = create_root(device.Get(), writer_desc); if (mesh && GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57", nullptr, 0)) - return native_fixed_mesh_fixture(device.Get(), guest.Get(), writer.Get(), log_path); + return native_fixed_mesh_fixture(device.Get(), guest.Get(), writer.Get(), log_path, warp); wchar_t mesh86_dir[MAX_PATH]{}; if (mesh && GetEnvironmentVariableW(L"X2W_MESH86_FIXTURE_DIR", mesh86_dir, MAX_PATH)) { const bool depth_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH", nullptr, 0) != 0; @@ -2814,12 +3037,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]{}; @@ -2877,6 +3104,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); @@ -3222,7 +3456,7 @@ int main(int argc, char** argv) try if (indexed) { // Forwarded: the three unrefused runs. Other reasons: the short argument range, the invalid index range and two commands. refuse_each_reason(guest.Get(), signature.Get()); - const std::string line = indirect_line(guest.Get(), log_path); + const std::string line = render_totals_line(guest.Get(), log_path, "x2w-render indirect:"); DeleteFileW(log_path.c_str()); const std::string expected = std::string("x2w-render indirect: forwarded: drawindexed ") + (count_control ? "4" : "3") + "; refused graphics-pipeline: drawindexed 1; compute-pipeline: dispatch 1; placeholder-signature: other 1; "