From 5df33e0b1e326f6869ec147d9ca58d2e301843ef Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 28 Nov 2026 23:31:07 +0000 Subject: [PATCH 1/7] runtime: opt-in immediate slot 57 mesh for indirect DispatchMesh X2W_MESH57_DERIVE_STATE=1 builds one desktop mesh pipeline from a single immediate GS_ALLOC_REQ when no reviewed profile was opened, then the existing ExecuteIndirect path forwards it. The switch off leaves every current refusal unchanged. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- CMakeLists.txt | 11 ++ docs/experiments/native-fixed-mesh57.md | 18 +++ docs/startup-runtime.md | 1 + src/startup_stubs/d3d12_capture.inl | 2 + src/startup_stubs/d3d12_xs_device.cpp | 19 +++ src/startup_stubs/mesh57_alloc.h | 100 ++++++++++++++++ src/startup_stubs/native_mesh57.inl | 148 ++++++++++++++++++++++++ tests/mesh57_derive_alloc_check.cpp | 94 +++++++++++++++ tests/startup_indirect_draw_indexed.cpp | 121 ++++++++++++++++++- 9 files changed, 512 insertions(+), 2 deletions(-) create mode 100644 src/startup_stubs/mesh57_alloc.h create mode 100644 tests/mesh57_derive_alloc_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 252816910f..c9b4860da2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1913,6 +1913,11 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_mesh_xmem_writer_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_MESH86_FIXTURE_XMEM=$") endforeach() +add_executable(mesh57_derive_alloc_check tests/mesh57_derive_alloc_check.cpp src/gfx1013_isa.cpp) +target_include_directories(mesh57_derive_alloc_check PRIVATE src src/startup_stubs) +target_compile_features(mesh57_derive_alloc_check PRIVATE cxx_std_17) +add_test(NAME mesh57_derive_alloc COMMAND mesh57_derive_alloc_check) + get_filename_component(DXC_BIN_DIR "${DXC_EXECUTABLE}" DIRECTORY) if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") @@ -1920,6 +1925,12 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed) + add_test(NAME startup_indirect_mesh_${mode}_${backend} + COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) + set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + endforeach() add_test(NAME native_fixed_mesh57_mrt_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_mrt_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index aa73960277..3f0eb566df 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -86,3 +86,21 @@ pixel entry. A creation archive alone preserves the two register blocks but does not assign hardware register meanings to their offsets. Reproduce the source-built positive and altered-stage controls with `ctest --preset dev --no-tests=error -R '^native_direct_mesh$'`. + +## Opt-in immediate allocation + +`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. + +The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings, and the guest root must be empty. + +Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The rasterizer is solid, cull none, and depth clip. Those three values are not read from the register block. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. + +A failed derivation is remembered for that pipeline. Attachment and root mismatches are not: a later direct list can still be the first accepted call. The desktop pipeline then keeps the color format of that call. + +From the x64 Windows build environment, with DXC available to the native shader stand-in: + +```powershell +ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" +``` + +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` supplies a profile file that does not match. Those four leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f448bb21f5..498084aeb6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1651,6 +1651,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_DRAW_MISSING_SHADER=1` | records a [diagnostic fallback draw](experiments/missing-shader-fallback.md) for direct, non-indexed triangle lists while the requested translation manifest is absent. Requires single-sample attachments and a guest viewport and scissor. The shader pair leaves the attachments untouched. The render totals report `missing shader fallback draws`. | | `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. | | `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_DERIVE_STATE=1` | experimental, with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`: a direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when no `.mesh57-state` file was opened. Depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `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 4f8e00c18e..1188706e22 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -48,6 +48,8 @@ struct PipelineInfo { 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. + mutable bool mesh57_reviewed_present = false; // A .mesh57-state file was opened for this pipeline. + mutable const char* mesh57_derive_reason = nullptr; // Opt-in derivation refused this pipeline for good. }; struct ViewRecord { // Capture the guest descriptor layout, independent of the desktop SDK. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 56dbe26c48..e874b76926 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -89,6 +89,7 @@ #include "gfx1013_compute_native.h" #include "gfx1013_pixel.h" #include "mesh_shader_pipeline.h" +#include "mesh57_alloc.h" #include #include "native_buffer_store_view.h" #include "shader_dxil_compiler.h" @@ -3735,6 +3736,10 @@ bool root_srv_at_draw() } LONG root_srv_copies_skipped, root_srv_copies_made; +#ifdef X2W_NATIVE_SHADERS +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass); +#endif + void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) { @@ -3815,6 +3820,20 @@ 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); +#ifdef X2W_NATIVE_SHADERS + // Opt-in only. A reviewed .mesh57-state profile is unchanged. With the switch off this + // block does not run and the refusal below stays the one every existing fixture expects. + if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && + x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { + if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { + static LONG derived_mesh_refusals; + if (first_calls(derived_mesh_refusals, 16)) + log("x2w-render derived slot57 mesh refused: %s", why); + } else if (pass.pipeline->own().real) { + pass.indirect_graphics = pass.pipeline->own().indirect_graphics; + } + } +#endif 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))) { diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h new file mode 100644 index 0000000000..c6baa5ba62 --- /dev/null +++ b/src/startup_stubs/mesh57_alloc.h @@ -0,0 +1,100 @@ +// Opt-in slot 57 mesh layout for X2W_MESH57_DERIVE_STATE. +// +// A reviewed .mesh57-state profile still owns the MS entry layout. This reader accepts only the +// smallest program the mesh lowerer already runs: one s_mov_b32 of an integer immediate into m0 +// immediately before the only s_sendmsg GS_ALLOC_REQ (0xbf900009). The immediate is +// (primitives << 12) | vertices. Anything else, including the group-memory count exchange, stays +// refused so a captured program cannot invent threads, a wave size, or a group stride. +#pragma once + +#include "gfx1013_isa.h" + +#include +#include +#include +#include +#include + +namespace x2w_startup { + +struct MeshDerivedLayout { + unsigned threads = 0; + unsigned vertices = 0; + unsigned primitives = 0; + unsigned topology = 0; + unsigned group_stride = 0; + unsigned wave_size = 0; +}; + +// One wave64 group. group_stride stays 0: the accepted program does not read the group id, and the +// lowerer skips that multiply when the stride is 0. Returns empty when the program is not the +// single immediate allocation above, or when either count is outside 1..64. +inline std::optional derive_immediate_mesh_layout(std::string_view code) noexcept +{ + if (code.empty() || code.size() % 4 != 0) + return std::nullopt; + try { + bool previous_immediate = false; + std::uint32_t previous_word = 0; + unsigned allocations = 0; + unsigned vertices = 0; + unsigned primitives = 0; + bool wave32 = false; + bool exchange = false; + for (unsigned pc = 0; pc < code.size();) { + std::uint32_t raw = 0; + std::memcpy(&raw, code.data() + pc, sizeof(raw)); + const auto inst = x2w::gfx1013::instruction(code, pc); + if (inst.size == 0 || pc + inst.size > code.size()) + return std::nullopt; + if (raw == 0xbf8a0000u) + exchange = true; + if (raw == 0xbf900009u) { + if (!previous_immediate) + return std::nullopt; + const unsigned next_vertices = previous_word & 4095u; + const unsigned next_primitives = (previous_word >> 12) & 4095u; + if ((previous_word >> 24) != 0 || next_vertices == 0 || next_primitives == 0 || + next_vertices > 64u || next_primitives > 64u) + return std::nullopt; + vertices = next_vertices; + primitives = next_primitives; + ++allocations; + } + previous_immediate = false; + previous_word = 0; + if (inst.form == x2w::gfx1013::Form::sop1 && inst.name == "s_mov_b32") { + const unsigned dst = (raw >> 16) & 127u; + const unsigned src = raw & 255u; + if (dst == 126u) + wave32 = true; + if (dst == 124u) { + if (src >= 128u && src <= 192u) { + previous_immediate = true; + previous_word = static_cast(src - 128u); + } else if (src == 255u && inst.size >= 8u) { + std::uint32_t literal = 0; + std::memcpy(&literal, code.data() + pc + 4, sizeof(literal)); + previous_immediate = true; + previous_word = literal; + } + } + } + pc += inst.size; + } + if (allocations != 1 || wave32 || exchange) + return std::nullopt; + MeshDerivedLayout layout; + layout.threads = 64; + layout.vertices = vertices; + layout.primitives = primitives; + layout.topology = 2; + layout.group_stride = 0; + layout.wave_size = 64; + return layout; + } catch (...) { + return std::nullopt; + } +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index b8455b82d3..91a14fed4c 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -247,6 +247,9 @@ void prepare_native_mesh57(Wrapper* pipeline) std::ifstream file(std::filesystem::path(path), std::ios::binary); if (!file) return; + // A present profile keeps the reviewed gate even when its bytes do not match. The opt-in + // derivation below must not replace a file a person already supplied. + info->mesh57_reviewed_present = true; try { x2w_startup::Mesh57Profile profile{}; if (!file.read(reinterpret_cast(&profile), sizeof(profile))) @@ -447,4 +450,149 @@ void prepare_native_mesh57(Wrapper* pipeline) log("x2w-render native slot57 mesh %016llx refused: %s", key, e.what()); } } + +// Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no +// reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. +// A reason that depends on the command list (attachments, the bound root) is not remembered. +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) +{ + if (!pipeline || pipeline->own().real) + return nullptr; + const auto* info = pipeline_info(pipeline); + if (!info) + return "derived mesh has no captured pipeline"; + if (info->mesh57_derive_reason) + return info->mesh57_derive_reason; + auto remember = [&](const char* why) { + info->mesh57_derive_reason = why; + return why; + }; + wchar_t sdk[MAX_PATH]; + const DWORD sdk_length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (!sdk_length || sdk_length >= MAX_PATH) + return "derived mesh needs the native shader compiler"; + wchar_t cache[MAX_PATH]; + const DWORD cache_length = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache, MAX_PATH); + if (!cache_length || cache_length >= MAX_PATH) + return "derived mesh needs a shader cache"; + if (info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) + return remember("derived mesh needs a fixed slot 57 pair"); + if (info->mesh57_reviewed_present) + return remember("a reviewed mesh profile is present"); + u64 fields[0x300 / sizeof(u64)]{}; + std::memcpy(fields, info->desc.data(), sizeof(fields)); + 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 remember("derived mesh root or state lengths do not match"); + if (!root_info(root)->empty() || root_heap_flags(root)) + return remember("derived mesh keeps a non-empty guest root refused"); + if (info->state_a.size() < x2w_pipeline_state::a_layout + 4) + return remember("derived mesh state block is short"); + std::uint32_t layout_word = 0; + std::memcpy(&layout_word, info->state_a.data() + x2w_pipeline_state::a_layout, sizeof(layout_word)); + if (layout_word != x2w_pipeline_state::a_layout_mesh) + return remember("derived mesh requires the mesh layout word"); + const std::size_t shift = x2w_pipeline_state::a_mesh_shift; + if (info->state_a.size() < shift) + return remember("derived mesh state block is short"); + D3D12_BLEND_DESC blend{}; + const char* blend_why = nullptr; + // Blend words sit at +0xD0 in the vertex layout. The mesh layout shifts every field from +0x058 + // by +0x54, and the blend reader does not apply that shift itself. + if (!x2w_startup::state_block_blend(info->state_a.data() + shift, info->state_a.size() - shift, false, &blend, &blend_why)) + return remember(blend_why ? blend_why : "derived mesh blend was refused"); + x2w_pipeline_state::DepthStencilWords depth_words; + if (!x2w_pipeline_state::read_depth_stencil_words(info->state_a.data(), info->state_a.size(), depth_words)) + return remember("derived mesh state block is short for depth"); + const x2w_pipeline_state::DepthStencil depth = x2w_pipeline_state::decode_depth_stencil( + depth_words.depth, depth_words.stencil, depth_words.refmask, depth_words.refmask_bf); + if (!depth.ok) + return remember(depth.reason ? depth.reason : "derived mesh depth state was refused"); + if (depth.desc.DepthEnable || depth.desc.StencilEnable) + return remember("derived mesh keeps depth and stencil disabled"); + auto* desktop = static_cast(root->own().real); + if (!pass.targets_bound || !pass.viewport_set || !pass.scissor_set || !pass.targets_single_sample || + pass.target_count != 1 || !pass.target0 || pass.dsv_format != DXGI_FORMAT_UNKNOWN || + pass.target_formats[0] == DXGI_FORMAT_UNKNOWN) + return "derived mesh needs one single-sample color target, a viewport and a scissor"; + if (!pass.graphics_root || pass.graphics_root != desktop || pass.root != root_info(root) || pass.root_heap_flags) + return "derived mesh root is not the bound empty desktop root"; + const std::string ms(info->fixed_ms->begin(), info->fixed_ms->end()); + const auto layout = x2w_startup::derive_immediate_mesh_layout(ms); + if (!layout) + return remember("derived mesh needs one immediate allocation"); + try { + x2w::MeshStageLayout mesh_layout; + mesh_layout.threads = layout->threads; + mesh_layout.max_vertices = layout->vertices; + mesh_layout.max_primitives = layout->primitives; + mesh_layout.topology = layout->topology; + mesh_layout.group_stride = layout->group_stride; + mesh_layout.wave32 = false; + auto native = x2w::translate_mesh_program(ms, mesh_layout); + if (!native.constants.empty() || !native.bindings.empty() || !native.samplers.empty() || native.sampler_heap || + !native.mesh_heap_reads.empty()) + return remember("derived mesh program needs root or heap bindings"); + const std::string ps(info->fixed_ps->begin(), info->fixed_ps->end()); + const std::string ps_ir = x2w::direct_gfx1013_constant_pixel(ps); + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto cache_dir = std::filesystem::path(cache); + const auto ms_output = compiler.compile(native.dxil_ir, L"ms_6_6", cache_dir, x2w::ShaderSourceFormat::dxil_ir); + const auto ps_output = compiler.compile(ps_ir, L"ps_6_6", cache_dir, x2w::ShaderSourceFormat::dxil_ir); + x2w::meshlet::MeshOnlyPipelineStream stream{}; + stream.root_signature.value = reinterpret_cast(root); + stream.ms.value.pShaderBytecode = ms_output.dxil.data(); + stream.ms.value.BytecodeLength = ms_output.dxil.size(); + stream.ps.value.pShaderBytecode = ps_output.dxil.data(); + stream.ps.value.BytecodeLength = ps_output.dxil.size(); + stream.blend.value = blend; + stream.sample_mask.value = UINT_MAX; + stream.rasterizer.value = x2w_startup::default_pso_rasterizer(); + stream.depth_stencil.value = depth.desc; + D3D12_RT_FORMAT_ARRAY targets{}; + targets.NumRenderTargets = 1; + targets.RTFormats[0] = pass.target_formats[0]; + stream.rtv_formats.value = targets; + stream.dsv_format.value = DXGI_FORMAT_UNKNOWN; + DXGI_SAMPLE_DESC samples; + samples.Count = 1; + samples.Quality = 0; + stream.sample_desc.value = samples; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + D3D12_PIPELINE_STATE_STREAM_DESC desc; + desc.SizeInBytes = sizeof(stream); + desc.pPipelineStateSubobjectStream = &stream; + bool compute = false; + char why[256]{}; + IndirectGraphicsPipeline graphics; + ID3D12RootSignature* pipeline_root = nullptr; + auto* created = build_stream_pipeline(&desc, why, sizeof(why), compute, graphics, pipeline_root, desktop, true); + if (!created) { + log("x2w-render derived slot57 mesh desktop pipeline refused: %s", why); + if (pipeline->own().real) + return nullptr; + return remember("derived mesh desktop pipeline was refused"); + } + auto* pso = static_cast(created); + AcquireSRWLockExclusive(¬e_lock); + if (pipeline->own().real) { + ReleaseSRWLockExclusive(¬e_lock); + pso->Release(); + return nullptr; + } + pipeline->own().indirect_graphics = graphics; + if (pipeline_root) + pipeline->own().pipeline_root = pipeline_root; + pipeline->own().real = pso; + ReleaseSRWLockExclusive(¬e_lock); + log("x2w-render derived slot57 mesh ready"); + return nullptr; + } catch (const std::exception& e) { + log("x2w-render derived slot57 mesh refused: %s", e.what()); + if (pipeline->own().real) + return nullptr; + return remember("derived mesh translation was refused"); + } +} #endif diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp new file mode 100644 index 0000000000..1a8eede361 --- /dev/null +++ b/tests/mesh57_derive_alloc_check.cpp @@ -0,0 +1,94 @@ +// Host check for the opt-in immediate mesh allocation reader. No device and no shader compiler. +#include "mesh57_alloc.h" + +#include +#include +#include +#include +#include + +namespace { +int fail(const char* name) +{ + std::fprintf(stderr, "mesh57 derive alloc: %s\n", name); + return 1; +} + +std::string words_of(const std::uint32_t* words, std::size_t count) +{ + std::string out(count * sizeof(std::uint32_t), '\0'); + if (count) + std::memcpy(out.data(), words, count * sizeof(std::uint32_t)); + return out; +} + +bool accepted(std::string_view code, unsigned vertices, unsigned primitives) +{ + const auto layout = x2w_startup::derive_immediate_mesh_layout(code); + return layout && layout->vertices == vertices && layout->primitives == primitives && + layout->threads == 64 && layout->topology == 2 && layout->group_stride == 0 && + layout->wave_size == 64; +} +} // namespace + +int main() +{ + // Source-built triangle: m0 = (1 primitive << 12) | 3 vertices, then GS_ALLOC_REQ. + const std::uint32_t triangle[] = { + 0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, + 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + if (!accepted(words_of(triangle, sizeof(triangle) / sizeof(triangle[0])), 3, 1)) + return fail("triangle"); + + const std::uint32_t only_alloc[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf810000u}; + if (!accepted(words_of(only_alloc, 4), 3, 1)) + return fail("alloc alone"); + + const std::uint32_t endpgm[] = {0xbf810000u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(endpgm, 1))) + return fail("no allocation"); + + const std::uint32_t gap[] = {0xbefc03ffu, 0x1003u, 0xbf800000u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(gap, 4))) + return fail("instruction between m0 and GS_ALLOC_REQ"); + + const std::uint32_t twice[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbefc03ffu, 0x1003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(twice, 6))) + return fail("two allocations"); + + const std::uint32_t high[] = {0xbefc03ffu, 0x01001003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(high, 3))) + return fail("high byte"); + + const std::uint32_t zero[] = {0xbefc03ffu, 0u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(zero, 3))) + return fail("zero counts"); + + const std::uint32_t wide[] = {0xbefc03ffu, (1u << 12) | 65u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(wide, 3))) + return fail("count above one wave"); + + const std::uint32_t exchange[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf8a0000u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(exchange, 4))) + return fail("count exchange"); + + // s_mov_b32 exec_lo, 0. Wave32 writes exec with s_mov_b32; wave64 uses s_mov_b64. + const std::uint32_t wave32_mov = 0xbefe0380u; + std::string wave32_word(sizeof(wave32_mov), '\0'); + std::memcpy(wave32_word.data(), &wave32_mov, sizeof(wave32_mov)); + const auto decoded = x2w::gfx1013::instruction(wave32_word, 0); + if (decoded.name != "s_mov_b32") + return fail("exec_lo encoding"); + const std::uint32_t wave32[] = {wave32_mov, 0xbefc03ffu, 0x1003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(wave32, 4))) + return fail("wave32 exec move"); + + const std::uint32_t from_register[] = {0xbefc0300u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(from_register, 2))) + return fail("m0 from a register"); + + if (x2w_startup::derive_immediate_mesh_layout({})) + return fail("empty"); + return 0; +} diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 2cc49b9dc1..7568d43ca1 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -2343,6 +2344,114 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, return 0; } +// Opt-in X2W_MESH57_DERIVE_STATE. The source-built triangle has no .mesh57-state file. +// mesh-derived forwards one DispatchMesh and paints (2,0). The other modes must leave the clear color. +static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, const char* mode) +{ + struct CacheCleanup { + std::filesystem::path path; + ~CacheCleanup() + { + std::error_code error; + std::filesystem::remove_all(path, error); + } + }; + const bool enable = std::strcmp(mode, "mesh-derived-off") != 0; + check(SetEnvironmentVariableA("X2W_MESH57_DERIVE_STATE", enable ? "1" : nullptr) ? S_OK : E_FAIL, + "derived mesh switch"); + const auto prefix = "mesh57-derived-" + std::to_string(GetCurrentProcessId()) + "-"; + CacheCleanup cache; + for (unsigned attempt = 0;; ++attempt) { + cache.path = std::filesystem::current_path() / (prefix + std::to_string(attempt)); + if (std::filesystem::create_directory(cache.path)) + break; + } + check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.path.c_str()) ? S_OK : E_FAIL, "derived mesh cache"); + ComPtr blob; + D3D12_ROOT_SIGNATURE_DESC empty{}; + const auto root = create_root(guest, empty, &blob); + std::vector ms{0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, + 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + if (std::strcmp(mode, "mesh-derived-bad") == 0) + ms.assign(1, 0xbf810000u); + const std::vector ps{0x7e0002f2u, 0xf800180fu, 0u, 0xbf810000u}; + const auto ms_size = ms.size() * sizeof(UINT); + const auto ps_size = ps.size() * sizeof(UINT); + // Long enough for the mesh-shifted blend words (+0x124) and depth words (+0x10C). + constexpr std::size_t state_bytes = 0x144; + std::vector state_a(state_bytes, 0); + const std::uint32_t mesh_layout = 6; + std::memcpy(state_a.data() + 4, &mesh_layout, sizeof(mesh_layout)); + if (std::strcmp(mode, "mesh-derived-depth") == 0) { + const std::uint32_t depth_on = 2; + std::memcpy(state_a.data() + 0x10c, &depth_on, sizeof(depth_on)); + } + std::vector state_b(4, 0); + UINT64 fields[0x300 / sizeof(UINT64)]{}; + fields[2] = state_a.size(); + fields[4] = state_b.size(); + fields[6] = ps_size; + fields[14] = ms_size; + const auto fold = [](UINT64 key, const void* data, size_t n) { + const auto* bytes = static_cast(data); + for (size_t i = 0; i < n; ++i) + key = (key ^ bytes[i]) * 1099511628211ull; + return key; + }; + const char revision[] = "x2w-startup-mesh-57-3"; + UINT64 key = fold(1469598103934665603ull, revision, sizeof(revision) - 1); + const auto extend = [&](UINT64 base, const void* data, UINT64 n) { + return fold(fold(base, &n, sizeof(n)), data, static_cast(n)); + }; + key = extend(key, ms.data(), ms_size); + key = extend(key, ps.data(), ps_size); + key = extend(key, blob->GetBufferPointer(), blob->GetBufferSize()); + const UINT64 variant = extend(extend(extend(key, fields, sizeof(fields)), state_a.data(), state_a.size()), + state_b.data(), state_b.size()); + if (std::strcmp(mode, "mesh-derived-reviewed") == 0) { + char name[64]; + std::snprintf(name, sizeof(name), "%016llx.mesh57-state", static_cast(variant)); + std::ofstream out(cache.path / name, std::ios::binary); + const char marker = 'x'; + out.write(&marker, 1); + if (!out) + return 1; + } + 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[13] = reinterpret_cast(ms.data()); + ComPtr pso; + using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); + check(slot(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), reinterpret_cast(pso.GetAddressOf())), + "create derived mesh"); + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + D3D12_COMMAND_SIGNATURE_DESC signature_desc; + signature_desc.ByteStride = static_cast(sizeof(D3D12_DISPATCH_MESH_ARGUMENTS)); + signature_desc.NumArgumentDescs = 1; + signature_desc.pArgumentDescs = &argument; + signature_desc.NodeMask = 0; + ComPtr signature; + if (FAILED(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)))) { + std::puts("indirect mesh capability skip: DispatchMesh signature unavailable"); + return 77; + } + const auto work = writer_pipeline(device, writer, "write_one_mesh_group"); + x2w_startup::Mesh57Profile profile{}; + std::memcpy(profile.magic, "X2WM571", 8); + profile.targets.NumRenderTargets = 1; + profile.targets.RTFormats[0] = format; + profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + const int pixels = std::strcmp(mode, "mesh-derived") == 0 ? 1 : 2; + const bool painted = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, + nullptr, false, pixels, &profile); + return painted ? 0 : 1; +} + int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; @@ -2364,6 +2473,12 @@ int main(int argc, char** argv) try SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", nullptr) ? S_OK : E_FAIL, "enable loose XMem root SRV"); else if (lease_fixture && !lease_arguments) check(SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", "1") ? S_OK : E_FAIL, "enable mesh XMem handoff"); + const bool derived_off = argc == 3 && std::strcmp(argv[2], "mesh-derived-off") == 0; + const bool derived_bad = argc == 3 && std::strcmp(argv[2], "mesh-derived-bad") == 0; + const bool derived_depth = argc == 3 && std::strcmp(argv[2], "mesh-derived-depth") == 0; + const bool derived_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-reviewed") == 0; + const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || + (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; const bool copy_on = argc == 3 && std::strcmp(argv[2], "copy-provenance") == 0; @@ -2387,10 +2502,10 @@ int main(int argc, char** argv) try const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; else if (argc == 3 && std::strcmp(argv[2], "rect") == 0) kind = DrawKind::rect; - else if (lease_arguments || console_mesh || desktop_as || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) + else if (lease_arguments || console_mesh || desktop_as || derived_mesh || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) kind = DrawKind::mesh; else if (rect) kind = DrawKind::indexed_rect; - else if (argc != 2 && !count_control && !translated_indexed && !lease_writer) return 2; + else if (argc != 2 && !count_control && !translated_indexed && !lease_writer && !derived_mesh) return 2; const bool indexed = kind == DrawKind::indexed || kind == DrawKind::indexed_rect; const bool mesh = kind == DrawKind::mesh; const bool fixed_create_fixture = mesh && GetEnvironmentVariableA("X2W_FIXED_MESH_CREATE_FIXTURE", nullptr, 0); @@ -2473,6 +2588,8 @@ int main(int argc, char** argv) try 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()); + if (derived_mesh) + return derived_mesh_fixture(device.Get(), guest.Get(), writer.Get(), argv[2]); 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; From aed2c0c75192ef1c806092539db4e7c0aae14274 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 28 Nov 2026 23:35:12 +0000 Subject: [PATCH 2/7] runtime: limit derived mesh forwarding to slot 57 profile misses X2W_MESH57_DERIVE_STATE only attempts a direct DispatchMesh whose pipeline is slot 57 and has no desktop PSO. Draws and other mesh pipelines stay refused. A slot 57 pipeline with no captured stages stays refused too. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- CMakeLists.txt | 2 +- docs/experiments/native-fixed-mesh57.md | 6 ++++-- docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_xs_device.cpp | 8 ++++++-- tests/startup_indirect_draw_indexed.cpp | 15 +++++++++++---- 5 files changed, 23 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c9b4860da2..f171cc8c48 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1925,7 +1925,7 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") - foreach(mode derived derived-off derived-bad derived-depth derived-reviewed) + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated) add_test(NAME startup_indirect_mesh_${mode}_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 3f0eb566df..a0a01a54f4 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -89,7 +89,9 @@ source-built positive and altered-stage controls with ## Opt-in immediate allocation -`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. +`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that slot 57 pipeline. That is the `graphics/mesh_profile_missing` refusal: a slot 57 mesh with captured stages and no desktop pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. `graphics/no_translation` is a different refusal (no captured stages, or the call is not this slot 57 mesh) and this switch does not forward it. + +A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings, and the guest root must be empty. @@ -103,4 +105,4 @@ From the x64 Windows build environment, with DXC available to the native shader ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" ``` -`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` supplies a profile file that does not match. Those four leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` supplies a profile file that does not match. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program, so the switch has nothing to translate. Those five leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 498084aeb6..0ac02abb73 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1651,7 +1651,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_DRAW_MISSING_SHADER=1` | records a [diagnostic fallback draw](experiments/missing-shader-fallback.md) for direct, non-indexed triangle lists while the requested translation manifest is absent. Requires single-sample attachments and a guest viewport and scissor. The shader pair leaves the attachments untouched. The render totals report `missing shader fallback draws`. | | `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. | | `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_DERIVE_STATE=1` | experimental, with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`: a direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when no `.mesh57-state` file was opened. Depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`: addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `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_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index e874b76926..237917384e 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3821,9 +3821,13 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); #ifdef X2W_NATIVE_SHADERS - // Opt-in only. A reviewed .mesh57-state profile is unchanged. With the switch off this - // block does not run and the refusal below stays the one every existing fixture expects. + // Opt-in for the graphics/mesh_profile_missing refusal: a direct DispatchMesh whose slot 57 + // pipeline has no desktop PSO and no cached stage. Draws, and any mesh pipeline that is not + // slot 57, stay on the refusal below (graphics/no_translation among them). A reviewed + // .mesh57-state profile is unchanged. With the switch off this block does not run. + const PipelineInfo* derived_info = pass.pipeline ? pipeline_info(pass.pipeline) : nullptr; if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && + !pass.indirect_graphics.cached_mesh && derived_info && derived_info->path == 57 && x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { static LONG derived_mesh_refusals; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 7568d43ca1..785c3a0687 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2344,7 +2344,7 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, return 0; } -// Opt-in X2W_MESH57_DERIVE_STATE. The source-built triangle has no .mesh57-state file. +// Opt-in X2W_MESH57_DERIVE_STATE for a slot 57 mesh with captured stages and no reviewed profile. // mesh-derived forwards one DispatchMesh and paints (2,0). The other modes must leave the clear color. static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, const char* mode) { @@ -2421,8 +2421,14 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 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[13] = reinterpret_cast(ms.data()); + // No captured stages: the switch must not invent a translation. The call stays refused. + if (std::strcmp(mode, "mesh-derived-untranslated") == 0) { + fields[6] = 0; + fields[14] = 0; + } else { + fields[5] = reinterpret_cast(ps.data()); + fields[13] = reinterpret_cast(ms.data()); + } ComPtr pso; using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); check(slot(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), reinterpret_cast(pso.GetAddressOf())), @@ -2477,7 +2483,8 @@ int main(int argc, char** argv) try const bool derived_bad = argc == 3 && std::strcmp(argv[2], "mesh-derived-bad") == 0; const bool derived_depth = argc == 3 && std::strcmp(argv[2], "mesh-derived-depth") == 0; const bool derived_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-reviewed") == 0; - const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || + const bool derived_untranslated = argc == 3 && std::strcmp(argv[2], "mesh-derived-untranslated") == 0; + const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; From 075e46113f96fc5fa67fe1a49298880b6b0fddd7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 00:01:36 +0000 Subject: [PATCH 3/7] runtime: compile derived slot 57 meshes without the native frontend X2W_MESH57_DXC_DIR supplies dxcompiler.dll and dxil.dll to the slot 57 derivation alone. X2W_NATIVE_SHADERS stays unset for other programs and is only a fallback compiler directory for this path. A missing directory still logs the existing compiler refusal. A present .mesh57-state file is still honored when the native switch did not open it. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- CMakeLists.txt | 6 ++++ docs/experiments/native-fixed-mesh57.md | 8 +++-- docs/startup-runtime.md | 3 +- src/startup_stubs/native_mesh57.inl | 48 +++++++++++++++++++++++-- tests/startup_indirect_draw_indexed.cpp | 23 +++++++++--- 5 files changed, 79 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f171cc8c48..222a15b8b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1931,6 +1931,12 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") endforeach() + foreach(mode derived-dxc derived-dxc-reviewed) + add_test(NAME startup_indirect_mesh_${mode}_${backend} + COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) + set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_MESH57_DXC_DIR=${DXC_BIN_DIR}") + endforeach() add_test(NAME native_fixed_mesh57_mrt_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_mrt_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index a0a01a54f4..f91bfcb864 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -89,7 +89,11 @@ source-built positive and altered-stage controls with ## Opt-in immediate allocation -`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that slot 57 pipeline. That is the `graphics/mesh_profile_missing` refusal: a slot 57 mesh with captured stages and no desktop pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. `graphics/no_translation` is a different refusal (no captured stages, or the call is not this slot 57 mesh) and this switch does not forward it. +`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_SHADER_CACHE` and a compiler directory, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that slot 57 pipeline. That is the `graphics/mesh_profile_missing` refusal: a slot 57 mesh with captured stages and no desktop pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. `graphics/no_translation` is a different refusal (no captured stages, or the call is not this slot 57 mesh) and this switch does not forward it. + +`X2W_MESH57_DXC_DIR` is the directory of `dxcompiler.dll` and `dxil.dll` for this path alone. It does not turn on native translation for other graphics or compute programs. `X2W_NATIVE_SHADERS` is still accepted as the compiler directory for this one pipeline, and setting it also turns that other translation on. When neither directory is set, the call stays refused and the log says `derived mesh needs the native shader compiler`. + +On the Windows test PC at `aed2c0c7`, `X2W_MESH57_DERIVE_STATE=1` with no compiler directory logged that refusal and forwarded nothing. Setting `X2W_NATIVE_SHADERS` compiled this path and also translated other programs, which refused fixed graphics entries and compute views before any `ExecuteIndirect`. A startup run that wants only this path sets `X2W_MESH57_DERIVE_STATE=1`, `X2W_MESH57_DXC_DIR`, and `X2W_SHADER_CACHE`, and leaves `X2W_NATIVE_SHADERS` unset. A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. @@ -105,4 +109,4 @@ From the x64 Windows build environment, with DXC available to the native shader ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" ``` -`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` supplies a profile file that does not match. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program, so the switch has nothing to translate. Those five leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program, so the switch has nothing to translate. Those six leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0ac02abb73..f0da81d4ca 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1651,7 +1651,8 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_DRAW_MISSING_SHADER=1` | records a [diagnostic fallback draw](experiments/missing-shader-fallback.md) for direct, non-indexed triangle lists while the requested translation manifest is absent. Requires single-sample attachments and a guest viewport and scissor. The shader pair leaves the attachments untouched. The render totals report `missing shader fallback draws`. | | `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. | | `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_DERIVE_STATE=1` | experimental, with `X2W_NATIVE_SHADERS` and `X2W_SHADER_CACHE`: addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `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/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 91a14fed4c..00e24fb2e9 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -451,6 +451,49 @@ void prepare_native_mesh57(Wrapper* pipeline) } } +// The directory of dxcompiler.dll and dxil.dll for this path alone. X2W_MESH57_DXC_DIR does not +// turn on native translation for other programs. X2W_NATIVE_SHADERS remains a fallback so a run +// that already set it can still compile this one pipeline. +bool mesh57_derive_compiler_dir(wchar_t* sdk, DWORD capacity) +{ + DWORD length = GetEnvironmentVariableW(L"X2W_MESH57_DXC_DIR", sdk, capacity); + if (!length || length >= capacity) + length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, capacity); + return length && length < capacity; +} + +// Same variant name prepare_native_mesh57 opens. Used when that function did not run because +// X2W_NATIVE_SHADERS is unset. A present file keeps the reviewed gate; this path does not parse it. +bool mesh57_reviewed_file_present(const PipelineInfo* info) +{ + if (!info || info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) + return false; + u64 fields[0x300 / sizeof(u64)]; + std::memcpy(fields, info->desc.data(), sizeof(fields)); + auto* root = as_wrapper(reinterpret_cast(fields[0])); + if (!root || root->own().kind != root_signature_kind || fields[2] != info->state_a.size() || + fields[4] != info->state_b.size()) + return false; + std::vector root_blob; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + const auto it = root_blobs().find(root); + if (it == root_blobs().end()) + return false; + root_blob = it->second; + } + constexpr char revision[] = "x2w-startup-mesh-57-3"; + const u64 key = fnv_part(root_blob, fnv_part(*info->fixed_ps, fnv_part(*info->fixed_ms, + 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))); + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"", variant, L".mesh57-state")) + return false; + std::ifstream file(std::filesystem::path(path), std::ios::binary); + return static_cast(file); +} + // Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no // reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. // A reason that depends on the command list (attachments, the bound root) is not remembered. @@ -468,8 +511,7 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) return why; }; wchar_t sdk[MAX_PATH]; - const DWORD sdk_length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); - if (!sdk_length || sdk_length >= MAX_PATH) + if (!mesh57_derive_compiler_dir(sdk, MAX_PATH)) return "derived mesh needs the native shader compiler"; wchar_t cache[MAX_PATH]; const DWORD cache_length = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache, MAX_PATH); @@ -477,6 +519,8 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) return "derived mesh needs a shader cache"; if (info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) return remember("derived mesh needs a fixed slot 57 pair"); + if (!info->mesh57_reviewed_present && mesh57_reviewed_file_present(info)) + info->mesh57_reviewed_present = true; if (info->mesh57_reviewed_present) return remember("a reviewed mesh profile is present"); u64 fields[0x300 / sizeof(u64)]{}; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 785c3a0687..cf91d2e95f 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2345,7 +2345,9 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, } // Opt-in X2W_MESH57_DERIVE_STATE for a slot 57 mesh with captured stages and no reviewed profile. -// mesh-derived forwards one DispatchMesh and paints (2,0). The other modes must leave the clear color. +// mesh-derived and mesh-derived-dxc forward one DispatchMesh and paint (2,0). The other modes +// must leave the clear color. mesh-derived-dxc uses only X2W_MESH57_DXC_DIR and clears +// X2W_NATIVE_SHADERS before the call. static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, const char* mode) { struct CacheCleanup { @@ -2359,6 +2361,17 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 const bool enable = std::strcmp(mode, "mesh-derived-off") != 0; check(SetEnvironmentVariableA("X2W_MESH57_DERIVE_STATE", enable ? "1" : nullptr) ? S_OK : E_FAIL, "derived mesh switch"); + const bool dxc_only = std::strcmp(mode, "mesh-derived-dxc") == 0 || + std::strcmp(mode, "mesh-derived-dxc-reviewed") == 0; + if (dxc_only) { + wchar_t dir[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_MESH57_DXC_DIR", dir, MAX_PATH); + if (!length || length >= MAX_PATH) + return 1; + check(SetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr) ? S_OK : E_FAIL, "clear native shaders"); + if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) != 0) + return 1; + } const auto prefix = "mesh57-derived-" + std::to_string(GetCurrentProcessId()) + "-"; CacheCleanup cache; for (unsigned attempt = 0;; ++attempt) { @@ -2409,7 +2422,7 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 key = extend(key, blob->GetBufferPointer(), blob->GetBufferSize()); const UINT64 variant = extend(extend(extend(key, fields, sizeof(fields)), state_a.data(), state_a.size()), state_b.data(), state_b.size()); - if (std::strcmp(mode, "mesh-derived-reviewed") == 0) { + if (std::strcmp(mode, "mesh-derived-reviewed") == 0 || std::strcmp(mode, "mesh-derived-dxc-reviewed") == 0) { char name[64]; std::snprintf(name, sizeof(name), "%016llx.mesh57-state", static_cast(variant)); std::ofstream out(cache.path / name, std::ios::binary); @@ -2451,7 +2464,7 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 profile.targets.NumRenderTargets = 1; profile.targets.RTFormats[0] = format; profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - const int pixels = std::strcmp(mode, "mesh-derived") == 0 ? 1 : 2; + const int pixels = std::strcmp(mode, "mesh-derived") == 0 || std::strcmp(mode, "mesh-derived-dxc") == 0 ? 1 : 2; const bool painted = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, nullptr, false, pixels, &profile); @@ -2484,8 +2497,10 @@ int main(int argc, char** argv) try const bool derived_depth = argc == 3 && std::strcmp(argv[2], "mesh-derived-depth") == 0; const bool derived_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-reviewed") == 0; const bool derived_untranslated = argc == 3 && std::strcmp(argv[2], "mesh-derived-untranslated") == 0; + const bool derived_dxc = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc") == 0; + const bool derived_dxc_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc-reviewed") == 0; const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || - (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); + derived_dxc || derived_dxc_reviewed || (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; const bool copy_on = argc == 3 && std::strcmp(argv[2], "copy-provenance") == 0; From 0380d9e7f4dc8387b5738702ba50e8ec37dcb829 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 00:44:25 +0000 Subject: [PATCH 4/7] runtime: count every DispatchMesh derive refusal by reason The opt-in now records each DispatchMesh ExecuteIndirect, including calls that never enter slot 57 derivation. The fixed-pair check reports which clause failed, and the heartbeat prints the counts with one sample per reason. Captured stage bytes stay available for a later attempt while the switch is on. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- docs/experiments/native-fixed-mesh57.md | 26 ++++ docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_draw.inl | 8 +- src/startup_stubs/d3d12_xs_device.cpp | 47 +++++-- src/startup_stubs/mesh57_alloc.h | 157 ++++++++++++++++++++++++ src/startup_stubs/native_mesh57.inl | 83 ++++++++++++- tests/mesh57_derive_alloc_check.cpp | 78 ++++++++++++ 7 files changed, 384 insertions(+), 17 deletions(-) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index f91bfcb864..08b3b37e3d 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -95,6 +95,32 @@ source-built positive and altered-stage controls with On the Windows test PC at `aed2c0c7`, `X2W_MESH57_DERIVE_STATE=1` with no compiler directory logged that refusal and forwarded nothing. Setting `X2W_NATIVE_SHADERS` compiled this path and also translated other programs, which refused fixed graphics entries and compute views before any `ExecuteIndirect`. A startup run that wants only this path sets `X2W_MESH57_DERIVE_STATE=1`, `X2W_MESH57_DXC_DIR`, and `X2W_SHADER_CACHE`, and leaves `X2W_NATIVE_SHADERS` unset. +At `075e4611` the same PC ran 420 seconds with the derive switch and `X2W_MESH57_DXC_DIR` set and `X2W_NATIVE_SHADERS` unset. Menus stayed up. `DispatchMesh` `ExecuteIndirect` still refused 656,186 calls in the graphics-pipeline bucket and forwarded none. The log showed 16 lines, all `derived mesh needs a fixed slot 57 pair`. That 16 is the old log cap, not the number of calls that entered derivation. With the switch on, every `DispatchMesh` `ExecuteIndirect` is now counted, including ones that never enter derivation. + +Derivation still runs only for a direct list whose bound pipeline is slot 57, has no desktop pipeline, and has no cached mesh stage. Anything else is counted and left on the existing refusal: + +- `not a direct list` +- `no pipeline bound` +- `desktop pipeline already set` +- `cached mesh stage` +- `no pipeline record` +- `pipeline is slot 86` (a stream mesh, or a pipeline that already has a slot 86 key) +- `pipeline is a derived slot 55` (the sample's `base` is the slot of the pipeline it was derived from, when that chain stays inside slot 55) +- `pipeline is not slot 57` + +A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, the vertex span at `+0x48` is empty, the mesh length at `+0x70` is non-zero, and both the mesh and pixel bytes were copied at creation. Otherwise the call is counted under one of: + +- `slot 57 descriptor is shorter than the fixed prefix` (under 120 bytes, so the stage words were not read) +- `slot 57 descriptor is not 768 bytes` +- `slot 57 descriptor has a vertex span` (the capture skips the mesh and pixel copies) +- `slot 57 descriptor has no mesh stage length` +- `slot 57 mesh stage was not captured` (the bytes were unreadable or larger than 1 MiB) +- `slot 57 pixel stage was not captured` (no pixel bytes; a zero pixel span is not a program this path can compile) + +Those six still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. + +The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, and whether a desktop pipeline or a slot 86 key is present. The line has no file path. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason. `forwarded` is that count when derivation installs a desktop pipeline. + A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings, and the guest root must be empty. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f0da81d4ca..3665038871 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1652,7 +1652,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. | | `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_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, depth, stencil, a non-empty root, and any other allocation shape stay refused. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, slot 55, depth, stencil, a non-empty root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` with the counts. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `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_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1933d5f78e..8372b1e79a 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -902,8 +902,12 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo if (first && first_calls(logged, 12)) log("x2w-draw mesh request %016llx: slot57, MS %zu bytes, PS %zu bytes", key, mesh.size(), pixel.size()); - info->fixed_ms.reset(); - info->fixed_ps.reset(); + // The opt-in derivation reads these bytes on a later ExecuteIndirect. A retryable refusal + // (attachments, the bound root) must not become a permanent missing-stage refusal. + if (!x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { + info->fixed_ms.reset(); + info->fixed_ps.reset(); + } } } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 237917384e..b3eeb78527 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3738,6 +3738,8 @@ LONG root_srv_copies_skipped, root_srv_copies_made; #ifdef X2W_NATIVE_SHADERS const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass); +void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineInfo* info, int list_type); +void log_mesh57_derive_census(); #endif void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, @@ -3821,20 +3823,38 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); #ifdef X2W_NATIVE_SHADERS - // Opt-in for the graphics/mesh_profile_missing refusal: a direct DispatchMesh whose slot 57 - // pipeline has no desktop PSO and no cached stage. Draws, and any mesh pipeline that is not - // slot 57, stay on the refusal below (graphics/no_translation among them). A reviewed - // .mesh57-state profile is unchanged. With the switch off this block does not run. - const PipelineInfo* derived_info = pass.pipeline ? pipeline_info(pass.pipeline) : nullptr; - if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && - !pass.indirect_graphics.cached_mesh && derived_info && derived_info->path == 57 && - x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { - if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { - static LONG derived_mesh_refusals; - if (first_calls(derived_mesh_refusals, 16)) - log("x2w-render derived slot57 mesh refused: %s", why); + // Opt-in for one slot 57 shape. Every DispatchMesh is counted here when the switch is on, + // including calls that never enter derivation. Draws stay on the refusal below. + if (mesh && x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { + const PipelineInfo* derived_info = pass.pipeline ? pipeline_info(pass.pipeline) : nullptr; + const char* skip = nullptr; + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT) + skip = "not a direct list"; + else if (!pass.pipeline) + skip = "no pipeline bound"; + else if (pass.pipeline->own().real) + skip = "desktop pipeline already set"; + else if (pass.indirect_graphics.cached_mesh) + skip = "cached mesh stage"; + else if (!derived_info) + skip = "no pipeline record"; + else if (derived_info->path != 57) { + if (pass.pipeline->own().mesh86_key || derived_info->path == 86) + skip = "pipeline is slot 86"; + else if (derived_info->path == 55) + skip = "pipeline is a derived slot 55"; + else + skip = "pipeline is not slot 57"; + } + if (skip) { + record_mesh57_derive(skip, pass.pipeline, derived_info, static_cast(type)); + } else if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { + record_mesh57_derive(why, pass.pipeline, derived_info, static_cast(type)); } else if (pass.pipeline->own().real) { pass.indirect_graphics = pass.pipeline->own().indirect_graphics; + record_mesh57_derive("forwarded", pass.pipeline, pipeline_info(pass.pipeline), static_cast(type)); + } else { + record_mesh57_derive("derivation produced no pipeline", pass.pipeline, derived_info, static_cast(type)); } } #endif @@ -7703,6 +7723,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (n == start) n += std::snprintf(line + n, sizeof(line) - n, " 0"); } log("%s", line); +#ifdef X2W_NATIVE_SHADERS + log_mesh57_derive_census(); +#endif } if (render_mode() && frame % 300 == 0) { // Which command-list slots the title called in the last 300 frames, per frame. diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index c6baa5ba62..2701587bc4 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -97,4 +98,160 @@ inline std::optional derive_immediate_mesh_layout(std::string } } +// Why a slot 57 creation record is not the fixed mesh+pixel pair this path can read. +// nullptr means both stages were captured from a 768-byte descriptor with no vertex span. +// The clauses match the capture in note_pipeline: a vertex span, a zero mesh length, or a +// short descriptor leaves the stage pointers empty, and an unreadable stage is dropped. +struct Mesh57PairRecord { + std::size_t desc_bytes = 0; + bool mesh_captured = false; + bool pixel_captured = false; + std::uint64_t vertex_pointer = 0; + std::uint64_t vertex_bytes = 0; + std::uint64_t mesh_length = 0; + std::uint64_t pixel_length = 0; +}; + +inline const char* mesh57_fixed_pair_reason(const Mesh57PairRecord& record) noexcept +{ + if (record.desc_bytes < 15 * sizeof(std::uint64_t)) + return "slot 57 descriptor is shorter than the fixed prefix"; + if (record.desc_bytes != 0x300) + return "slot 57 descriptor is not 768 bytes"; + if (record.vertex_pointer || record.vertex_bytes) + return "slot 57 descriptor has a vertex span"; + if (!record.mesh_length) + return "slot 57 descriptor has no mesh stage length"; + if (!record.mesh_captured) + return "slot 57 mesh stage was not captured"; + if (!record.pixel_captured) + return "slot 57 pixel stage was not captured"; + (void)record.pixel_length; + return nullptr; +} + +// One sample of the bound pipeline for a DispatchMesh ExecuteIndirect the opt-in did not forward. +// Counts are call counts. The sample is the first call that used that reason. +struct Mesh57DeriveSample { + int path = 0; + int base_path = 0; + std::uint64_t key = 0; + std::uint32_t desc_bytes = 0; + std::uint32_t mesh_bytes = 0; + std::uint32_t pixel_bytes = 0; + std::uint32_t state_a = 0; + std::uint32_t state_b = 0; + std::uint32_t vertex_bytes = 0; + std::uint32_t mesh_length = 0; + std::uint32_t pixel_length = 0; + int list_type = 0; + int real = 0; + int mesh86 = 0; +}; + +struct Mesh57DeriveCensus { + static constexpr int capacity = 24; + struct Row { + const char* reason = nullptr; + std::uint64_t calls = 0; + Mesh57DeriveSample sample; + }; + Row rows[capacity]; + int used = 0; + std::uint64_t overflow_calls = 0; + + Mesh57DeriveCensus() + { + for (int i = 0; i < capacity; ++i) + rows[i] = Row(); + } + + // True the first time `reason` is stored. Later calls only add to the count. + // `reason` must be a stable literal; rows compare the pointer. + bool note(const char* reason, const Mesh57DeriveSample& sample) noexcept + { + if (!reason) + return false; + for (int i = 0; i < used; ++i) { + if (rows[i].reason == reason) { + rows[i].calls += 1; + return false; + } + } + if (used >= capacity) { + overflow_calls += 1; + return false; + } + rows[used].reason = reason; + rows[used].calls = 1; + rows[used].sample = sample; + used += 1; + return true; + } + + std::uint64_t total() const noexcept + { + std::uint64_t calls = overflow_calls; + for (int i = 0; i < used; ++i) + calls += rows[i].calls; + return calls; + } +}; + +inline std::size_t mesh57_derive_sample_line(const char* reason, const Mesh57DeriveSample& sample, + char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + const int n = std::snprintf(out, cap, + "x2w-render mesh57-derive sample reason=%s path=%d base=%d desc=%u ms=%u ps=%u state_a=%u state_b=%u " + "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d", + reason ? reason : "", sample.path, sample.base_path, sample.desc_bytes, sample.mesh_bytes, + sample.pixel_bytes, sample.state_a, sample.state_b, sample.vertex_bytes, sample.mesh_length, + sample.pixel_length, static_cast(sample.key), sample.list_type, sample.real, + sample.mesh86); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + +inline std::size_t mesh57_derive_summary_line(const Mesh57DeriveCensus& census, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (!census.total()) + return 0; + int n = std::snprintf(out, cap, "x2w-render mesh57-derive:"); + if (n < 0) { + out[0] = 0; + return 0; + } + for (int i = 0; i < census.used && static_cast(n) + 1 < cap; ++i) { + const int wrote = std::snprintf(out + n, cap - static_cast(n), "%s %s %llu", + i ? ";" : "", census.rows[i].reason ? census.rows[i].reason : "", + static_cast(census.rows[i].calls)); + if (wrote < 0) + break; + if (static_cast(n) + static_cast(wrote) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + n += wrote; + } + if (census.overflow_calls && static_cast(n) + 1 < cap) { + const int wrote = std::snprintf(out + n, cap - static_cast(n), "; unlisted %llu", + static_cast(census.overflow_calls)); + if (wrote > 0 && static_cast(n) + static_cast(wrote) < cap) + n += wrote; + } + return static_cast(n); +} + } // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 00e24fb2e9..6affd33a07 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -494,6 +494,73 @@ bool mesh57_reviewed_file_present(const PipelineInfo* info) return static_cast(file); } +x2w_startup::Mesh57DeriveCensus mesh57_derive_census; +SRWLOCK mesh57_derive_census_lock = SRWLOCK_INIT; + +std::uint32_t mesh57_derive_u32(std::size_t value) +{ + return value > 0xffffffffu ? 0xffffffffu : static_cast(value); +} + +x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const PipelineInfo* info, int list_type) +{ + x2w_startup::Mesh57DeriveSample sample; + sample.list_type = list_type; + if (!pipeline) + return sample; + sample.real = pipeline->own().real ? 1 : 0; + sample.mesh86 = pipeline->own().mesh86_key ? 1 : 0; + sample.key = known_pipeline_key(pipeline); + const PipelineInfo* base = info; + for (int depth = 0; base && base->path == 55 && base->base && depth < 8; ++depth) + base = pipeline_info(base->base); + if (base && base != info) + sample.base_path = base->path; + if (!info) + return sample; + sample.path = info->path; + sample.desc_bytes = mesh57_derive_u32(info->desc.size()); + sample.mesh_bytes = info->fixed_ms ? mesh57_derive_u32(info->fixed_ms->size()) : 0; + sample.pixel_bytes = info->fixed_ps ? mesh57_derive_u32(info->fixed_ps->size()) : 0; + sample.state_a = mesh57_derive_u32(info->state_a.size()); + sample.state_b = mesh57_derive_u32(info->state_b.size()); + if (info->desc.size() >= 15 * sizeof(u64)) { + u64 words[15]; + std::memcpy(words, info->desc.data(), sizeof(words)); + sample.vertex_bytes = mesh57_derive_u32(static_cast(words[10])); + sample.pixel_length = mesh57_derive_u32(static_cast(words[6])); + sample.mesh_length = mesh57_derive_u32(static_cast(words[14])); + } + return sample; +} + +void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineInfo* info, int list_type) +{ + const x2w_startup::Mesh57DeriveSample sample = mesh57_derive_sample(pipeline, info, list_type); + bool first = false; + AcquireSRWLockExclusive(&mesh57_derive_census_lock); + first = mesh57_derive_census.note(reason, sample); + ReleaseSRWLockExclusive(&mesh57_derive_census_lock); + if (!first) + return; + char line[640]; + if (x2w_startup::mesh57_derive_sample_line(reason, sample, line, sizeof(line))) + log("%s", line); +} + +void log_mesh57_derive_census() +{ + if (!x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) + return; + x2w_startup::Mesh57DeriveCensus copy; + AcquireSRWLockShared(&mesh57_derive_census_lock); + copy = mesh57_derive_census; + ReleaseSRWLockShared(&mesh57_derive_census_lock); + char line[2048]; + if (x2w_startup::mesh57_derive_summary_line(copy, line, sizeof(line))) + log("%s", line); +} + // Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no // reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. // A reason that depends on the command list (attachments, the bound root) is not remembered. @@ -517,8 +584,20 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) const DWORD cache_length = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache, MAX_PATH); if (!cache_length || cache_length >= MAX_PATH) return "derived mesh needs a shader cache"; - if (info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) - return remember("derived mesh needs a fixed slot 57 pair"); + x2w_startup::Mesh57PairRecord pair; + pair.desc_bytes = info->desc.size(); + pair.mesh_captured = static_cast(info->fixed_ms); + pair.pixel_captured = static_cast(info->fixed_ps); + if (info->desc.size() >= 15 * sizeof(u64)) { + u64 words[15]; + std::memcpy(words, info->desc.data(), sizeof(words)); + pair.vertex_pointer = words[9]; + pair.vertex_bytes = words[10]; + pair.pixel_length = words[6]; + pair.mesh_length = words[14]; + } + if (const char* pair_why = x2w_startup::mesh57_fixed_pair_reason(pair)) + return remember(pair_why); if (!info->mesh57_reviewed_present && mesh57_reviewed_file_present(info)) info->mesh57_reviewed_present = true; if (info->mesh57_reviewed_present) diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index 1a8eede361..06eaa38f38 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -90,5 +90,83 @@ int main() if (x2w_startup::derive_immediate_mesh_layout({})) return fail("empty"); + + x2w_startup::Mesh57PairRecord pair; + pair.desc_bytes = 0x300; + pair.mesh_captured = true; + pair.pixel_captured = true; + pair.mesh_length = 64; + pair.pixel_length = 16; + if (x2w_startup::mesh57_fixed_pair_reason(pair)) + return fail("fixed pair"); + pair.desc_bytes = 64; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor is shorter than the fixed prefix") != 0) + return fail("short descriptor"); + pair.desc_bytes = 256; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor is not 768 bytes") != 0) + return fail("descriptor length"); + pair.desc_bytes = 0x300; + pair.vertex_pointer = 0x1000; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor has a vertex span") != 0) + return fail("vertex span"); + pair.vertex_pointer = 0; + pair.mesh_length = 0; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor has no mesh stage length") != 0) + return fail("mesh length"); + pair.mesh_length = 64; + pair.mesh_captured = false; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 mesh stage was not captured") != 0) + return fail("mesh stage"); + pair.mesh_captured = true; + pair.pixel_captured = false; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 pixel stage was not captured") != 0) + return fail("pixel stage"); + + x2w_startup::Mesh57DeriveCensus census; + x2w_startup::Mesh57DeriveSample slot86; + slot86.path = 86; + slot86.mesh86 = 1; + slot86.desc_bytes = 512; + if (!census.note("pipeline is slot 86", slot86)) + return fail("first slot 86 note"); + slot86.path = 57; + if (census.note("pipeline is slot 86", slot86) || census.rows[0].calls != 2 || census.rows[0].sample.path != 86) + return fail("slot 86 count keeps the first sample"); + x2w_startup::Mesh57DeriveSample missing_ps; + missing_ps.path = 57; + missing_ps.desc_bytes = 0x300; + missing_ps.mesh_bytes = 128; + if (!census.note("slot 57 pixel stage was not captured", missing_ps) || census.total() != 3) + return fail("pixel stage count"); + char summary[512]; + const auto summary_n = x2w_startup::mesh57_derive_summary_line(census, summary, sizeof(summary)); + if (!summary_n || !std::strstr(summary, "pipeline is slot 86 2") || + !std::strstr(summary, "slot 57 pixel stage was not captured 1") || + std::strncmp(summary, "x2w-render mesh57-derive:", 25) != 0) + return fail("summary"); + char sample[512]; + if (!x2w_startup::mesh57_derive_sample_line(census.rows[0].reason, census.rows[0].sample, sample, sizeof(sample)) || + !std::strstr(sample, "reason=pipeline is slot 86") || !std::strstr(sample, "path=86") || + !std::strstr(sample, "desc=512") || std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) + return fail("sample"); + x2w_startup::Mesh57DeriveCensus full; + if (!full.note("overflow-probe", slot86)) + return fail("overflow first"); + const char* extras[] = { + "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", + "r21", "r22", "r23"}; + for (const char* extra : extras) { + if (!full.note(extra, slot86)) + return fail("fill census"); + } + if (full.note("r24", slot86) || full.overflow_calls != 1 || full.used != full.capacity) + return fail("census overflow"); return 0; } From f358a2ed4187bb981cbd72115dc0777ae55a141b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 00:51:19 +0000 Subject: [PATCH 5/7] runtime: match mesh derive reasons by text, not address MSVC does not give two copies of the same reason string the same address, so the census treated the second note as a new reason and kept that sample. Rows now compare the characters. The host check uses two distinct copies. Refs #870 Refs #2413 Co-authored-by: SimSalabimse --- src/startup_stubs/mesh57_alloc.h | 7 ++++--- tests/mesh57_derive_alloc_check.cpp | 10 ++++++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index 2701587bc4..14aea8f6e5 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -166,14 +166,15 @@ struct Mesh57DeriveCensus { rows[i] = Row(); } - // True the first time `reason` is stored. Later calls only add to the count. - // `reason` must be a stable literal; rows compare the pointer. + // True the first time this reason text is stored. Later calls only add to the count. + // The row keeps the first pointer, so that pointer must outlive the census. Matching is by + // text: two copies of the same characters are one reason. String-literal addresses are not. bool note(const char* reason, const Mesh57DeriveSample& sample) noexcept { if (!reason) return false; for (int i = 0; i < used; ++i) { - if (rows[i].reason == reason) { + if (rows[i].reason && std::strcmp(rows[i].reason, reason) == 0) { rows[i].calls += 1; return false; } diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index 06eaa38f38..b6980db283 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -133,10 +133,16 @@ int main() slot86.path = 86; slot86.mesh86 = 1; slot86.desc_bytes = 512; - if (!census.note("pipeline is slot 86", slot86)) + // Two objects with the same characters. A compiler that does not pool string literals gives + // them different addresses; they are still one reason. + char first_reason[] = "pipeline is slot 86"; + char second_reason[] = "pipeline is slot 86"; + if (&first_reason[0] == &second_reason[0]) + return fail("reason copies are the same object"); + if (!census.note(first_reason, slot86)) return fail("first slot 86 note"); slot86.path = 57; - if (census.note("pipeline is slot 86", slot86) || census.rows[0].calls != 2 || census.rows[0].sample.path != 86) + if (census.note(second_reason, slot86) || census.rows[0].calls != 2 || census.rows[0].sample.path != 86) return fail("slot 86 count keeps the first sample"); x2w_startup::Mesh57DeriveSample missing_ps; missing_ps.path = 57; From 5433113756bb84f599712ae82bc53d49d92e1464 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 01:23:31 +0000 Subject: [PATCH 6/7] runtime: bind one derived mesh constant and reuse slot 55 bases A DispatchMesh derivation now copies a single guest constant block of 1..8 dwords into desktop b0, including a heap-indexed root whose only parameter is that block. Descriptor roots and other heap-indexed shapes stay refused by name. A slot 55 pipeline uses its slot 57 base when every patch is a blend record. The heartbeat adds the derived forward count. Co-authored-by: SimSalabimse --- CMakeLists.txt | 2 +- docs/experiments/native-fixed-mesh57.md | 16 ++- docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_xs_device.cpp | 27 +++-- src/startup_stubs/mesh57_alloc.h | 120 ++++++++++++++++++- src/startup_stubs/native_mesh57.inl | 147 ++++++++++++++++++++++-- tests/mesh57_derive_alloc_check.cpp | 60 +++++++++- tests/startup_indirect_draw_indexed.cpp | 69 ++++++++++- 8 files changed, 408 insertions(+), 35 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 222a15b8b6..11a167c866 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1925,7 +1925,7 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") - foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated) + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated derived-root derived-root-unset derived-root-table derived-slot55 derived-slot55-mask) add_test(NAME startup_indirect_mesh_${mode}_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index 08b3b37e3d..d510147b16 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -97,7 +97,7 @@ On the Windows test PC at `aed2c0c7`, `X2W_MESH57_DERIVE_STATE=1` with no compil At `075e4611` the same PC ran 420 seconds with the derive switch and `X2W_MESH57_DXC_DIR` set and `X2W_NATIVE_SHADERS` unset. Menus stayed up. `DispatchMesh` `ExecuteIndirect` still refused 656,186 calls in the graphics-pipeline bucket and forwarded none. The log showed 16 lines, all `derived mesh needs a fixed slot 57 pair`. That 16 is the old log cap, not the number of calls that entered derivation. With the switch on, every `DispatchMesh` `ExecuteIndirect` is now counted, including ones that never enter derivation. -Derivation still runs only for a direct list whose bound pipeline is slot 57, has no desktop pipeline, and has no cached mesh stage. Anything else is counted and left on the existing refusal: +Derivation runs for a direct list whose bound pipeline is slot 57, or slot 55 whose base chain ends at slot 57, when that pipeline has no desktop pipeline and no cached mesh stage. Anything else is counted and left on the existing refusal: - `not a direct list` - `no pipeline bound` @@ -105,7 +105,7 @@ Derivation still runs only for a direct list whose bound pipeline is slot 57, ha - `cached mesh stage` - `no pipeline record` - `pipeline is slot 86` (a stream mesh, or a pipeline that already has a slot 86 key) -- `pipeline is a derived slot 55` (the sample's `base` is the slot of the pipeline it was derived from, when that chain stays inside slot 55) +- `pipeline is a derived slot 55` (the base chain does not end at slot 57) - `pipeline is not slot 57` A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, the vertex span at `+0x48` is empty, the mesh length at `+0x70` is non-zero, and both the mesh and pixel bytes were copied at creation. Otherwise the call is counted under one of: @@ -119,11 +119,15 @@ A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, Those six still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. -The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, and whether a desktop pipeline or a slot 86 key is present. The line has no file path. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason. `forwarded` is that count when derivation installs a desktop pipeline. +The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, and the guest root (`root`, `const`, `other`, `heap`). The line has no file path. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. -The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings, and the guest root must be empty. +The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings. + +An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords and no other parameters is bound, including when the guest root is heap indexed: user SGPR s8 is that block, and the draw copies it into a desktop b0 the same way a reviewed constant profile does. The constant words must already be set on the list. The heap base itself is not bound; a shader that reads it is refused by the lowerer. A heap-indexed root with any other shape (`derived mesh guest root is heap indexed`), a descriptor or root descriptor (`derived mesh guest root has descriptors`), or any other constant shape (`derived mesh guest root constants do not fit one user block`) stays refused. Those need a reviewed SGPR map; this path does not invent one. + +A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Any other record stays refused (`slot 55 patches are not applied`). The base's shader, root, and depth rules are unchanged. Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The rasterizer is solid, cull none, and depth clip. Those three values are not read from the register block. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. @@ -135,4 +139,6 @@ From the x64 Windows build environment, with DXC available to the native shader ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" ``` -`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program, so the switch has nothing to translate. Those six leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader without a device. +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8, with the word set, and paints the same texel. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the root decision, the slot 55 patch rule, and the forwards line without a device. + +On the Windows test PC at `f358a2ed`, a 420 second run with `X2W_TRANSLATED_INDIRECT_DRAW=1`, `X2W_MESH57_DERIVE_STATE=1`, and `X2W_MESH57_DXC_DIR` set forwarded nothing. The derive census was `slot 57 pixel stage was not captured` 47823, `derived mesh keeps a non-empty guest root refused` 152144, and `pipeline is a derived slot 55` 180066. The non-empty sample had both stages (mesh 9536 bytes, pixel 4352 bytes). The slot 55 sample was a 332-byte descriptor whose base was slot 57 and whose stage lengths were unread. That root refusal is replaced by the three root reasons above, and a slot 55 call now uses its slot 57 base when the patches are blend records. A 4352-byte pixel is still not a constant export, and a program that is not the one immediate allocation is still refused. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 3665038871..a3963683e3 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1652,7 +1652,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. | | `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_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. `graphics/no_translation`, slot 86, slot 55, depth, stencil, a non-empty root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` with the counts. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `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_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index b3eeb78527..e8fa91f1f8 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -168,6 +168,8 @@ struct IndirectGraphicsPipeline { const std::vector* guest_root_params{}; UINT cached_srv_root = UINT_MAX; UINT constant_guest = UINT_MAX; // Single MS b0 mapped from this guest root under a deferred signature. + // Opt-in derived mesh: constant_guest names one guest constant block, and the guest root is not heap indexed. + bool plain_constants = false; }; // Why a resource is outside the retire class (X2W_D3D12_RELEASE_RETIRED), decided at creation, and why it left it later. @@ -3737,7 +3739,9 @@ bool root_srv_at_draw() LONG root_srv_copies_skipped, root_srv_copies_made; #ifdef X2W_NATIVE_SHADERS -const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass); +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_DESC* blend_override = nullptr, + const PipelineInfo* source = nullptr); +const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass); void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineInfo* info, int list_type); void log_mesh57_derive_census(); #endif @@ -3838,17 +3842,15 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, skip = "cached mesh stage"; else if (!derived_info) skip = "no pipeline record"; - else if (derived_info->path != 57) { - if (pass.pipeline->own().mesh86_key || derived_info->path == 86) - skip = "pipeline is slot 86"; - else if (derived_info->path == 55) - skip = "pipeline is a derived slot 55"; - else - skip = "pipeline is not slot 57"; - } + else if (pass.pipeline->own().mesh86_key || derived_info->path == 86) + skip = "pipeline is slot 86"; + else if (derived_info->path != 57 && derived_info->path != 55) + skip = "pipeline is not slot 57"; + const bool slot55 = !skip && derived_info && derived_info->path == 55; if (skip) { record_mesh57_derive(skip, pass.pipeline, derived_info, static_cast(type)); - } else if (const char* why = derive_slot57_mesh(pass.pipeline, pass)) { + } else if (const char* why = slot55 ? derive_slot55_mesh(pass.pipeline, pass) + : derive_slot57_mesh(pass.pipeline, pass)) { record_mesh57_derive(why, pass.pipeline, derived_info, static_cast(type)); } else if (pass.pipeline->own().real) { pass.indirect_graphics = pass.pipeline->own().indirect_graphics; @@ -3889,7 +3891,10 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, !std::equal(pso.cached_targets, pso.cached_targets + pso.cached_target_count, pass.target_formats)) return refuse("cached mesh requires matching color and depth attachments, viewport and scissor", indirect_other, indirect_other_refusal_code::cached_mesh_attachments); - if (!pass.root || pass.root != pso.guest_root_params || (pass.root_heap_flags != 0) != (pso.constant_guest != UINT_MAX)) + const bool mapped = pso.constant_guest != UINT_MAX; + const bool indexing_matches = (pass.root_heap_flags != 0) == mapped || + (pso.plain_constants && pass.root_heap_flags == 0 && mapped); + if (!pass.root || pass.root != pso.guest_root_params || !indexing_matches) return refuse("cached mesh creation root or indexing mode differs", indirect_graphics_pipeline); for (std::size_t i = 0; i < pass.root->size(); ++i) { if (i == pso.cached_srv_root || (pso.constant_guest != UINT_MAX && i != pso.constant_guest)) continue; diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index 14aea8f6e5..d931fe8cf1 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -147,8 +147,94 @@ struct Mesh57DeriveSample { int list_type = 0; int real = 0; int mesh86 = 0; + // Guest root at creation. type 0 in Mesh57RootParameterView is a 32-bit constant block. + // other counts every parameter that is not one. heap is the heap-indexing flag word. + std::uint32_t root_parameters = 0; + std::uint32_t root_constant_dwords = 0; + std::uint32_t root_other = 0; + std::uint32_t root_heap = 0; }; +// One guest root parameter, without a D3D12 type. type 0 is 32-bit constants and +// constants is that block's dword count. Any other type is not a constant block. +struct Mesh57RootParameterView { + unsigned type = 0; + unsigned constants = 0; +}; + +// User SGPRs for a derived mesh start at s8, one dword per constant, in parameter +// order. That is the layout the mesh lowerer checks against the root signature. +// Only one constant block of 1..8 dwords fits the desktop b0 the draw path already copies. +struct Mesh57RootContract { + unsigned parameters = 0; + unsigned constant_dwords = 0; + unsigned other_parameters = 0; + unsigned heap_flags = 0; + bool bind_constants = false; + unsigned sgpr = 0; +}; + +inline Mesh57RootContract mesh57_root_contract(const Mesh57RootParameterView* params, unsigned count, + unsigned heap_flags) noexcept +{ + Mesh57RootContract out; + out.parameters = count; + out.heap_flags = heap_flags; + out.sgpr = 8; + // A heap-indexing flag does not by itself name a descriptor. One constant block is still + // copied into desktop b0; a shader that also reads the heap is refused by the lowerer. + bool constants_only = count == 1 && params; + if (constants_only) { + out.constant_dwords = params[0].constants; + constants_only = params[0].type == 0 && params[0].constants >= 1 && params[0].constants <= 8 && + out.sgpr <= 106 && params[0].constants <= 106 - out.sgpr; + } + for (unsigned i = 0; i < count; ++i) { + if (!params || params[i].type != 0) + out.other_parameters += 1; + else if (count != 1) + out.constant_dwords += params[i].constants; + } + out.bind_constants = constants_only; + return out; +} + +// nullptr when this root can take the existing empty path or the one-block constant path. +// Anything else stays refused: a descriptor or a heap flag needs a reviewed SGPR map. +inline const char* mesh57_root_bind_reason(const Mesh57RootContract& contract) noexcept +{ + if (contract.bind_constants) + return nullptr; + if (contract.parameters == 0 && contract.heap_flags == 0) + return nullptr; + if (contract.heap_flags) + return "derived mesh guest root is heap indexed"; + if (contract.other_parameters) + return "derived mesh guest root has descriptors"; + if (!contract.bind_constants) + return "derived mesh guest root constants do not fit one user block"; + return nullptr; +} + +// A slot 55 patch list can reuse a slot 57 mesh when it is empty or every record is a +// blend patch. record bytes are the 0x14c blend record (tag word plus the blend state). +// A tag other than 2, or a size that is not a whole number of records, is not applied. +inline const char* mesh57_slot55_patch_reason(const unsigned char* records, std::size_t bytes) noexcept +{ + constexpr std::size_t record = 0x14c; + if (!bytes) + return nullptr; + if (!records || bytes % record) + return "slot 55 patches are not applied"; + for (std::size_t at = 0; at < bytes; at += record) { + std::uint32_t tag = 0; + std::memcpy(&tag, records + at, sizeof(tag)); + if (tag != 2) + return "slot 55 patches are not applied"; + } + return nullptr; +} + struct Mesh57DeriveCensus { static constexpr int capacity = 24; struct Row { @@ -206,11 +292,11 @@ inline std::size_t mesh57_derive_sample_line(const char* reason, const Mesh57Der return 0; const int n = std::snprintf(out, cap, "x2w-render mesh57-derive sample reason=%s path=%d base=%d desc=%u ms=%u ps=%u state_a=%u state_b=%u " - "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d", + "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d root=%u const=%u other=%u heap=%u", reason ? reason : "", sample.path, sample.base_path, sample.desc_bytes, sample.mesh_bytes, sample.pixel_bytes, sample.state_a, sample.state_b, sample.vertex_bytes, sample.mesh_length, sample.pixel_length, static_cast(sample.key), sample.list_type, sample.real, - sample.mesh86); + sample.mesh86, sample.root_parameters, sample.root_constant_dwords, sample.root_other, sample.root_heap); if (n < 0) { out[0] = 0; return 0; @@ -255,4 +341,34 @@ inline std::size_t mesh57_derive_summary_line(const Mesh57DeriveCensus& census, return static_cast(n); } +// Calls whose reason text is "forwarded": a derived pipeline installed a desktop PSO. +inline std::uint64_t mesh57_derive_forwarded(const Mesh57DeriveCensus& census) noexcept +{ + for (int i = 0; i < census.used; ++i) { + if (census.rows[i].reason && std::strcmp(census.rows[i].reason, "forwarded") == 0) + return census.rows[i].calls; + } + return 0; +} + +inline std::size_t mesh57_derive_forwards_line(const Mesh57DeriveCensus& census, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (!census.total()) + return 0; + const int n = std::snprintf(out, cap, "x2w-render mesh57-derive forwards: %llu", + static_cast(mesh57_derive_forwarded(census))); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + } // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 6affd33a07..f2d1c65c31 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -531,6 +531,30 @@ x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const Pi sample.pixel_length = mesh57_derive_u32(static_cast(words[6])); sample.mesh_length = mesh57_derive_u32(static_cast(words[14])); } + const PipelineInfo* root_source = info; + for (int depth = 0; root_source && root_source->path == 55 && root_source->base && depth < 8; ++depth) + root_source = pipeline_info(root_source->base); + if (root_source && root_source->desc.size() >= sizeof(u64)) { + u64 root_bits = 0; + std::memcpy(&root_bits, root_source->desc.data(), sizeof(root_bits)); + auto* root = as_wrapper(reinterpret_cast(root_bits)); + if (root && root->own().kind == root_signature_kind) { + sample.root_heap = root_heap_flags(root); + if (const auto* params = root_info(root)) { + sample.root_parameters = mesh57_derive_u32(params->size()); + for (const auto& parameter : *params) { + if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + if (sample.root_constant_dwords <= ~std::uint32_t{0} - parameter.constants_count) + sample.root_constant_dwords += parameter.constants_count; + else + sample.root_constant_dwords = ~std::uint32_t{0}; + } else if (sample.root_other != ~std::uint32_t{0}) { + sample.root_other += 1; + } + } + } + } + } return sample; } @@ -559,16 +583,49 @@ void log_mesh57_derive_census() char line[2048]; if (x2w_startup::mesh57_derive_summary_line(copy, line, sizeof(line))) log("%s", line); + if (x2w_startup::mesh57_derive_forwards_line(copy, line, sizeof(line))) + log("%s", line); +} + +const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass) +{ + if (!pipeline || pipeline->own().real) + return nullptr; + const auto* info = pipeline_info(pipeline); + if (!info) + return "derived mesh has no captured pipeline"; + if (info->mesh57_derive_reason) + return info->mesh57_derive_reason; + Wrapper* base = info->base; + const PipelineInfo* base_info = nullptr; + for (int depth = 0; base && depth < 8; ++depth) { + base_info = pipeline_info(base); + if (!base_info || base_info->path != 55) + break; + base = base_info->base; + base_info = nullptr; + } + if (!base_info || base_info->path != 57) + return "pipeline is a derived slot 55"; + if (const char* patch = x2w_startup::mesh57_slot55_patch_reason(info->desc.data(), info->desc.size())) { + info->mesh57_derive_reason = patch; + return patch; + } + D3D12_BLEND_DESC blend{}; + std::size_t where = 0; + const bool has_blend = x2w_derived_blend::last_blend(info->desc.data(), info->desc.size(), blend, where); + return derive_slot57_mesh(pipeline, pass, has_blend ? &blend : nullptr, base_info); } // Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no // reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. // A reason that depends on the command list (attachments, the bound root) is not remembered. -const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_DESC* blend_override, + const PipelineInfo* source) { if (!pipeline || pipeline->own().real) return nullptr; - const auto* info = pipeline_info(pipeline); + const auto* info = source ? source : pipeline_info(pipeline); if (!info) return "derived mesh has no captured pipeline"; if (info->mesh57_derive_reason) @@ -608,8 +665,28 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) 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 remember("derived mesh root or state lengths do not match"); - if (!root_info(root)->empty() || root_heap_flags(root)) - return remember("derived mesh keeps a non-empty guest root refused"); + const auto* guest_parameters = root_info(root); + x2w_startup::Mesh57RootParameterView root_views[16]; + unsigned root_view_count = 0; + if (guest_parameters && guest_parameters->size() <= 16) { + root_view_count = static_cast(guest_parameters->size()); + for (unsigned i = 0; i < root_view_count; ++i) { + const auto& parameter = (*guest_parameters)[i]; + root_views[i].type = parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS ? 0u : 1u; + root_views[i].constants = parameter.constants_count; + } + } + const auto root_contract = x2w_startup::mesh57_root_contract( + root_view_count ? root_views : nullptr, root_view_count, root_heap_flags(root)); + if (guest_parameters && guest_parameters->size() > 16) + return remember("derived mesh guest root constants do not fit one user block"); + if (const char* root_why = x2w_startup::mesh57_root_bind_reason(root_contract)) + return remember(root_why); + if (root_contract.bind_constants) { + const auto mask = static_cast((1u << root_views[0].constants) - 1u); + if ((pass.constant_words_bound[0] & mask) != mask) + return "derived mesh root constants are incomplete"; + } if (info->state_a.size() < x2w_pipeline_state::a_layout + 4) return remember("derived mesh state block is short"); std::uint32_t layout_word = 0; @@ -622,8 +699,10 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) D3D12_BLEND_DESC blend{}; const char* blend_why = nullptr; // Blend words sit at +0xD0 in the vertex layout. The mesh layout shifts every field from +0x058 - // by +0x54, and the blend reader does not apply that shift itself. - if (!x2w_startup::state_block_blend(info->state_a.data() + shift, info->state_a.size() - shift, false, &blend, &blend_why)) + // by +0x54, and the blend reader does not apply that shift itself. A slot 55 blend patch replaces it. + if (blend_override) + blend = *blend_override; + else if (!x2w_startup::state_block_blend(info->state_a.data() + shift, info->state_a.size() - shift, false, &blend, &blend_why)) return remember(blend_why ? blend_why : "derived mesh blend was refused"); x2w_pipeline_state::DepthStencilWords depth_words; if (!x2w_pipeline_state::read_depth_stencil_words(info->state_a.data(), info->state_a.size(), depth_words)) @@ -639,8 +718,10 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) pass.target_count != 1 || !pass.target0 || pass.dsv_format != DXGI_FORMAT_UNKNOWN || pass.target_formats[0] == DXGI_FORMAT_UNKNOWN) return "derived mesh needs one single-sample color target, a viewport and a scissor"; - if (!pass.graphics_root || pass.graphics_root != desktop || pass.root != root_info(root) || pass.root_heap_flags) - return "derived mesh root is not the bound empty desktop root"; + ID3D12RootSignature* bound_root = pass.root_heap_flags ? pass.deferred_root : pass.graphics_root; + if (!bound_root || bound_root != desktop || pass.root != root_info(root) || + (pass.root_heap_flags && !root_contract.bind_constants)) + return "derived mesh root is not the bound desktop root"; const std::string ms(info->fixed_ms->begin(), info->fixed_ms->end()); const auto layout = x2w_startup::derive_immediate_mesh_layout(ms); if (!layout) @@ -653,8 +734,25 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) mesh_layout.topology = layout->topology; mesh_layout.group_stride = layout->group_stride; mesh_layout.wave32 = false; - auto native = x2w::translate_mesh_program(ms, mesh_layout); - if (!native.constants.empty() || !native.bindings.empty() || !native.samplers.empty() || native.sampler_heap || + D3D12_ROOT_PARAMETER1 constant_parameter{}; + D3D12_ROOT_SIGNATURE_DESC1 constant_root{}; + if (root_contract.bind_constants) { + mesh_layout.root_inputs.push_back({root_contract.sgpr, 0u, root_views[0].constants}); + constant_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + constant_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + constant_parameter.Constants.Num32BitValues = root_views[0].constants; + constant_root.NumParameters = 1; + constant_root.pParameters = &constant_parameter; + } + auto native = root_contract.bind_constants + ? x2w::translate_mesh_program(ms, mesh_layout, constant_root) + : x2w::translate_mesh_program(ms, mesh_layout); + const bool constants_match = !root_contract.bind_constants || + (native.constants.size() == 1 && native.constants[0].root_parameter == 0 && + native.constants[0].first_sgpr == root_contract.sgpr && + native.constants[0].count == root_views[0].constants); + if (!constants_match || (root_contract.bind_constants ? false : !native.constants.empty()) || + !native.bindings.empty() || !native.samplers.empty() || native.sampler_heap || !native.mesh_heap_reads.empty()) return remember("derived mesh program needs root or heap bindings"); const std::string ps(info->fixed_ps->begin(), info->fixed_ps->end()); @@ -688,9 +786,27 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) desc.pPipelineStateSubobjectStream = &stream; bool compute = false; char why[256]{}; + x2w_startup::ComPtr host; + if (root_contract.bind_constants) { + D3D12_ROOT_PARAMETER host_parameter{}; + host_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + host_parameter.Constants.Num32BitValues = (root_views[0].constants + 3u) & ~3u; + D3D12_ROOT_SIGNATURE_DESC host_desc; + host_desc.NumParameters = 1; + host_desc.pParameters = &host_parameter; + host_desc.NumStaticSamplers = 0; + host_desc.pStaticSamplers = nullptr; + host_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + x2w_startup::ComPtr host_blob; + if (FAILED(D3D12SerializeRootSignature(&host_desc, D3D_ROOT_SIGNATURE_VERSION_1, &host_blob, nullptr)) || + FAILED(device_of(the_device)->CreateRootSignature(0, host_blob->GetBufferPointer(), host_blob->GetBufferSize(), + IID_PPV_ARGS(&host)))) + return remember("derived mesh constant root was refused"); + } IndirectGraphicsPipeline graphics; ID3D12RootSignature* pipeline_root = nullptr; - auto* created = build_stream_pipeline(&desc, why, sizeof(why), compute, graphics, pipeline_root, desktop, true); + auto* created = build_stream_pipeline(&desc, why, sizeof(why), compute, graphics, pipeline_root, + host ? host.Get() : desktop, true); if (!created) { log("x2w-render derived slot57 mesh desktop pipeline refused: %s", why); if (pipeline->own().real) @@ -698,6 +814,15 @@ const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass) return remember("derived mesh desktop pipeline was refused"); } auto* pso = static_cast(created); + if (root_contract.bind_constants) { + static constexpr GUID lifetime{0xf74c6928, 0xb063, 0x4a00, {0xa5, 0xf0, 0x79, 0xe3, 0x60, 0xa4, 0xf1, 0x09}}; + if (FAILED(pso->SetPrivateDataInterface(lifetime, host.Get()))) { + pso->Release(); + return remember("derived mesh constant root was refused"); + } + graphics.constant_guest = 0; + graphics.plain_constants = root_heap_flags(root) == 0; + } AcquireSRWLockExclusive(¬e_lock); if (pipeline->own().real) { ReleaseSRWLockExclusive(¬e_lock); diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index b6980db283..73ed5094c3 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -159,8 +159,66 @@ int main() char sample[512]; if (!x2w_startup::mesh57_derive_sample_line(census.rows[0].reason, census.rows[0].sample, sample, sizeof(sample)) || !std::strstr(sample, "reason=pipeline is slot 86") || !std::strstr(sample, "path=86") || - !std::strstr(sample, "desc=512") || std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) + !std::strstr(sample, "desc=512") || !std::strstr(sample, "root=0") || + !std::strstr(sample, "const=0") || !std::strstr(sample, "other=0") || !std::strstr(sample, "heap=0") || + std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) return fail("sample"); + x2w_startup::Mesh57RootParameterView one; + one.type = 0; + one.constants = 1; + const auto bound = x2w_startup::mesh57_root_contract(&one, 1, 0); + if (!bound.bind_constants || bound.sgpr != 8 || bound.constant_dwords != 1 || + x2w_startup::mesh57_root_bind_reason(bound)) + return fail("one constant block"); + x2w_startup::Mesh57RootParameterView two[2]; + two[0].type = 0; + two[0].constants = 1; + two[1].type = 0; + two[1].constants = 1; + const auto split = x2w_startup::mesh57_root_contract(two, 2, 0); + if (split.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(split), + "derived mesh guest root constants do not fit one user block") != 0) + return fail("two constant blocks"); + x2w_startup::Mesh57RootParameterView table; + table.type = 1; + table.constants = 0; + const auto described = x2w_startup::mesh57_root_contract(&table, 1, 0); + if (described.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(described), + "derived mesh guest root has descriptors") != 0) + return fail("descriptor root"); + const auto heaped = x2w_startup::mesh57_root_contract(&one, 1, 0x8); + if (!heaped.bind_constants || x2w_startup::mesh57_root_bind_reason(heaped)) + return fail("heap plus one constant"); + const auto heap_only = x2w_startup::mesh57_root_contract(nullptr, 0, 0x8); + if (heap_only.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(heap_only), + "derived mesh guest root is heap indexed") != 0) + return fail("heap only"); + one.constants = 9; + const auto wide_root = x2w_startup::mesh57_root_contract(&one, 1, 0); + if (wide_root.bind_constants || !x2w_startup::mesh57_root_bind_reason(wide_root)) + return fail("wide constant block"); + const auto empty = x2w_startup::mesh57_root_contract(nullptr, 0, 0); + if (empty.bind_constants || x2w_startup::mesh57_root_bind_reason(empty)) + return fail("empty root"); + unsigned char blend_record[0x14c]; + std::memset(blend_record, 0, sizeof(blend_record)); + const std::uint32_t blend_tag = 2; + std::memcpy(blend_record, &blend_tag, sizeof(blend_tag)); + if (x2w_startup::mesh57_slot55_patch_reason(nullptr, 0) || + x2w_startup::mesh57_slot55_patch_reason(blend_record, sizeof(blend_record))) + return fail("blend patch"); + blend_record[0] = 1; + if (std::strcmp(x2w_startup::mesh57_slot55_patch_reason(blend_record, sizeof(blend_record)), + "slot 55 patches are not applied") != 0 || + std::strcmp(x2w_startup::mesh57_slot55_patch_reason(blend_record, 4), + "slot 55 patches are not applied") != 0) + return fail("unknown patch"); + if (!census.note("forwarded", slot86) || x2w_startup::mesh57_derive_forwarded(census) != 1) + return fail("forwarded count"); + char forwards[128]; + if (!x2w_startup::mesh57_derive_forwards_line(census, forwards, sizeof(forwards)) || + std::strcmp(forwards, "x2w-render mesh57-derive forwards: 1") != 0) + return fail("forwards line"); x2w_startup::Mesh57DeriveCensus full; if (!full.note("overflow-probe", slot86)) return fail("overflow first"); diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index cf91d2e95f..274245fec4 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1113,6 +1113,11 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ ComPtr fixed_source_heap; slot(wrapped, 25)(wrapped, graphics); slot(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); + if (label && std::strcmp(label, "mesh-derived-root") == 0) { + using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); + const UINT value = 0; + slot(wrapped, 40)(wrapped, 0, 1, &value, 0); + } if (leased) { using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot(wrapped, 44)(wrapped, 0, leased->address); @@ -2382,10 +2387,31 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.path.c_str()) ? S_OK : E_FAIL, "derived mesh cache"); ComPtr blob; D3D12_ROOT_SIGNATURE_DESC empty{}; + const bool constant_root = std::strcmp(mode, "mesh-derived-root") == 0 || + std::strcmp(mode, "mesh-derived-root-unset") == 0; + const bool table_root = std::strcmp(mode, "mesh-derived-root-table") == 0; + D3D12_ROOT_PARAMETER parameter{}; + D3D12_DESCRIPTOR_RANGE range{}; + if (constant_root) { + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameter.Constants.Num32BitValues = 1; + empty.NumParameters = 1; + empty.pParameters = ¶meter; + } else if (table_root) { + range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + range.NumDescriptors = 1; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable.NumDescriptorRanges = 1; + parameter.DescriptorTable.pDescriptorRanges = ⦥ + empty.NumParameters = 1; + empty.pParameters = ¶meter; + } const auto root = create_root(guest, empty, &blob); std::vector ms{0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + if (constant_root) + ms.insert(ms.begin(), 0xbe890308u); // s_mov_b32 s9, s8. s8 is the one guest constant at user SGPR 8. if (std::strcmp(mode, "mesh-derived-bad") == 0) ms.assign(1, 0xbf810000u); const std::vector ps{0x7e0002f2u, 0xf800180fu, 0u, 0xbf810000u}; @@ -2446,6 +2472,36 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); check(slot(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), reinterpret_cast(pso.GetAddressOf())), "create derived mesh"); + const bool slot55 = std::strcmp(mode, "mesh-derived-slot55") == 0 || + std::strcmp(mode, "mesh-derived-slot55-mask") == 0; + ComPtr derived; + if (slot55) { + std::vector patch; + const void* patch_bytes = nullptr; + UINT patch_count = 0; + if (std::strcmp(mode, "mesh-derived-slot55-mask") == 0) { + D3D12_BLEND_DESC blend{}; + auto& target = blend.RenderTarget[0]; + target.SrcBlend = D3D12_BLEND_ONE; + target.DestBlend = D3D12_BLEND_ZERO; + target.BlendOp = D3D12_BLEND_OP_ADD; + target.SrcBlendAlpha = D3D12_BLEND_ONE; + target.DestBlendAlpha = D3D12_BLEND_ZERO; + target.BlendOpAlpha = D3D12_BLEND_OP_ADD; + target.LogicOp = D3D12_LOGIC_OP_NOOP; + target.RenderTargetWriteMask = 0; + patch.resize(sizeof(std::uint32_t) + sizeof(blend)); + const std::uint32_t tag = 2; + std::memcpy(patch.data(), &tag, sizeof(tag)); + std::memcpy(patch.data() + sizeof(tag), &blend, sizeof(blend)); + patch_bytes = patch.data(); + patch_count = 1; + } + using Derive = HRESULT (WINAPI*)(IUnknown*, void*, UINT, const void*, REFIID, void**); + check(slot(guest, 55)(guest, pso.Get(), patch_count, patch_bytes, __uuidof(ID3D12PipelineState), + reinterpret_cast(derived.GetAddressOf())), + "create slot 55 mesh"); + } D3D12_INDIRECT_ARGUMENT_DESC argument{}; argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; D3D12_COMMAND_SIGNATURE_DESC signature_desc; @@ -2464,8 +2520,10 @@ static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D1 profile.targets.NumRenderTargets = 1; profile.targets.RTFormats[0] = format; profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - const int pixels = std::strcmp(mode, "mesh-derived") == 0 || std::strcmp(mode, "mesh-derived-dxc") == 0 ? 1 : 2; - const bool painted = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + const int pixels = std::strcmp(mode, "mesh-derived") == 0 || std::strcmp(mode, "mesh-derived-dxc") == 0 || + std::strcmp(mode, "mesh-derived-root") == 0 || std::strcmp(mode, "mesh-derived-slot55") == 0 ? 1 : 2; + const bool painted = run(device, guest, writer, work.Get(), root.Get(), slot55 ? derived.Get() : pso.Get(), + signature.Get(), DrawKind::mesh, false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, nullptr, false, pixels, &profile); return painted ? 0 : 1; @@ -2499,8 +2557,13 @@ int main(int argc, char** argv) try const bool derived_untranslated = argc == 3 && std::strcmp(argv[2], "mesh-derived-untranslated") == 0; const bool derived_dxc = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc") == 0; const bool derived_dxc_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc-reviewed") == 0; + const bool derived_root = argc == 3 && (std::strcmp(argv[2], "mesh-derived-root") == 0 || + std::strcmp(argv[2], "mesh-derived-root-unset") == 0 || std::strcmp(argv[2], "mesh-derived-root-table") == 0); + const bool derived_slot55 = argc == 3 && (std::strcmp(argv[2], "mesh-derived-slot55") == 0 || + std::strcmp(argv[2], "mesh-derived-slot55-mask") == 0); const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || - derived_dxc || derived_dxc_reviewed || (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); + derived_dxc || derived_dxc_reviewed || derived_root || derived_slot55 || + (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; const bool copy_on = argc == 3 && std::strcmp(argv[2], "copy-provenance") == 0; From 35b0d542fa8fcafa695264cf66e3cb855ba7c1eb Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 01:44:52 +0000 Subject: [PATCH 7/7] runtime: name unknown slot 55 tags and record root parameter types A slot 55 record that is not a blend tag stays refused, and the reason names the tag. The sample lists the first patch tags and sizes and the first guest-root parameter types. A zero pixel length is an empty descriptor span, not a dropped copy. No reviewed mesh user-SGPR map covers a five-parameter heap-indexed root, so that shape stays refused. Co-authored-by: SimSalabimse --- docs/experiments/native-fixed-mesh57.md | 15 +- docs/startup-runtime.md | 2 +- src/startup_stubs/mesh57_alloc.h | 195 ++++++++++++++++++++++-- src/startup_stubs/native_mesh57.inl | 70 ++++++++- tests/mesh57_derive_alloc_check.cpp | 73 ++++++++- 5 files changed, 325 insertions(+), 30 deletions(-) diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index d510147b16..c993777c3b 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -115,11 +115,12 @@ A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, - `slot 57 descriptor has a vertex span` (the capture skips the mesh and pixel copies) - `slot 57 descriptor has no mesh stage length` - `slot 57 mesh stage was not captured` (the bytes were unreadable or larger than 1 MiB) -- `slot 57 pixel stage was not captured` (no pixel bytes; a zero pixel span is not a program this path can compile) +- `slot 57 pixel stage is absent from the descriptor` (the pixel pointer and the pixel length are both zero; the mesh copy is kept) +- `slot 57 pixel stage was not captured` (the descriptor names a pixel span whose bytes were not kept) -Those six still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. +Those seven still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. -The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, and the guest root (`root`, `const`, `other`, `heap`). The line has no file path. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. +The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, the guest root (`root`, `const`, `other`, `heap`), the first parameter types (`params`), and the first slot 55 patch tags and sizes (`patches`). The line has no file path. `params` uses `t` for a descriptor table, `cN` for an N-dword constant block, `cbv`, `srv`, and `uav`. `patches` uses `tag:bytes`. A sample with no root parameters or no patch list prints `-`. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. @@ -127,7 +128,7 @@ The accepted program writes `m0` with one `s_mov_b32` of an integer immediate an An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords and no other parameters is bound, including when the guest root is heap indexed: user SGPR s8 is that block, and the draw copies it into a desktop b0 the same way a reviewed constant profile does. The constant words must already be set on the list. The heap base itself is not bound; a shader that reads it is refused by the lowerer. A heap-indexed root with any other shape (`derived mesh guest root is heap indexed`), a descriptor or root descriptor (`derived mesh guest root has descriptors`), or any other constant shape (`derived mesh guest root constants do not fit one user block`) stays refused. Those need a reviewed SGPR map; this path does not invent one. -A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Any other record stays refused (`slot 55 patches are not applied`). The base's shader, root, and depth rules are unchanged. +A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Tag 2 is the only slot 55 record this repository applies: the graphics path reads that blend descriptor and does not apply any other tag. Depth and raster for a slot 57 base come from its state block, not from a patch tag. A record whose tag is not 2 stays refused, and the reason names that tag (for example `slot 55 patch tag 3 is not applied`). A list whose size is not a whole number of 0x14c records stays `slot 55 patches are not applied`. The sample lists the first records either way. The base's shader, root, and depth rules are unchanged. Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The rasterizer is solid, cull none, and depth clip. Those three values are not read from the register block. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. @@ -142,3 +143,9 @@ ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirec `startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8, with the word set, and paints the same texel. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the root decision, the slot 55 patch rule, and the forwards line without a device. On the Windows test PC at `f358a2ed`, a 420 second run with `X2W_TRANSLATED_INDIRECT_DRAW=1`, `X2W_MESH57_DERIVE_STATE=1`, and `X2W_MESH57_DXC_DIR` set forwarded nothing. The derive census was `slot 57 pixel stage was not captured` 47823, `derived mesh keeps a non-empty guest root refused` 152144, and `pipeline is a derived slot 55` 180066. The non-empty sample had both stages (mesh 9536 bytes, pixel 4352 bytes). The slot 55 sample was a 332-byte descriptor whose base was slot 57 and whose stage lengths were unread. That root refusal is replaced by the three root reasons above, and a slot 55 call now uses its slot 57 base when the patches are blend records. A 4352-byte pixel is still not a constant export, and a program that is not the one immediate allocation is still refused. + +On the Windows test PC at `54331137`, the same switches, a 420 second run, forwarded nothing (`x2w-render mesh57-derive forwards: 0`). The census was `derived mesh guest root is heap indexed` 353719, `slot 57 pixel stage was not captured` 130628, and `slot 55 patches are not applied` 514994. The heap-indexed sample was path 57, descriptor 768, mesh 9536, pixel 4352, state A 504, state B 80, root 5, one constant dword, four other parameters, heap 1024. The pixel sample was path 57, mesh 1408, pixel length 0, state A 464, root 5, two constant dwords, four other parameters, heap 3072. The slot 55 sample was one 332-byte record on a slot 57 base with that same five-parameter root and heap 3072. + +The capture copies a pixel stage only when its length is non-zero and the bytes are readable. A zero pointer and a zero length is an empty span: the copy is skipped and the mesh bytes stay. The 1408-byte mesh in that sample was kept, so the pixel words in the creation descriptor were zero. An unreadable non-zero span fails the snapshot and drops both stages; this sample is not that case, and nothing writes the pixel stage after creation. A slot 55 record is state, not a shader. This path does not invent a pixel shader. A zero pixel length is now `slot 57 pixel stage is absent from the descriptor`. + +Heap 1024 is the view-heap flag (`0x400`). Heap 3072 is that flag plus the sampler-heap flag (`0xC00`). No reviewed map in this repository assigns user SGPRs for a five-parameter heap-indexed root on the mesh path. The maps that do exist are different ABIs. Raw graphics, and the reflected graphics path, start user SGPRs at s8: a descriptor table is one SGPR, a 32-bit constant block is one SGPR per dword, and a root CBV, SRV, or UAV is two SGPRs, with the heaps following when their flags are set. That layout is for a graphics stage. Direct compute without a reflected stage starts at s4 with the same parameter packing, and both heap flags occupy the next two SGPRs only when they exactly fill the user SGPR count. The 1024 sample has only the view-heap flag, and s4 is the compute ABI. A reviewed `.mesh57-state` profile stores the SGPR, the root parameter, and the count for that one program. These pipelines have no such file. The missing map is the physical user SGPR of each of the five parameters, and the user SGPR of the resource heap (and of the sampler heap when `0x800` is set). The stored root parameter keeps the type, and for a constant block the dword count; a descriptor table's ranges are not kept. This path does not guess the SGPRs. The sample line records the types so the map can be raised with the measured parameter kinds. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a3963683e3..4318ed5eaf 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1652,7 +1652,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. | | `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_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | -| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. A patch whose tag is not 2 stays refused and the reason names that tag. The sample line lists the first root-parameter types and the first patch tags. A zero pixel length in the descriptor stays refused (`slot 57 pixel stage is absent from the descriptor`). `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `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/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h index d931fe8cf1..4d3dced9ee 100644 --- a/src/startup_stubs/mesh57_alloc.h +++ b/src/startup_stubs/mesh57_alloc.h @@ -102,6 +102,7 @@ inline std::optional derive_immediate_mesh_layout(std::string // nullptr means both stages were captured from a 768-byte descriptor with no vertex span. // The clauses match the capture in note_pipeline: a vertex span, a zero mesh length, or a // short descriptor leaves the stage pointers empty, and an unreadable stage is dropped. +// A zero pixel length is an empty span in the descriptor, not a copy that failed. struct Mesh57PairRecord { std::size_t desc_bytes = 0; bool mesh_captured = false; @@ -112,6 +113,32 @@ struct Mesh57PairRecord { std::uint64_t pixel_length = 0; }; +// One stage copy, matching note_pipeline's snapshot. readable is the caller's check of the +// guest bytes; this function does not read them. A zero length and a zero pointer is an empty +// span and the copy is skipped. A zero length with a pointer, or a non-zero length that is +// not readable, fails the copy. note_pipeline then drops both stages. +enum class Mesh57StageCopy : unsigned { empty = 0, copied = 1, unreadable = 2 }; + +inline Mesh57StageCopy mesh57_stage_copy(std::uint64_t pointer, std::uint64_t bytes, bool readable) noexcept +{ + if (!bytes) + return pointer ? Mesh57StageCopy::unreadable : Mesh57StageCopy::empty; + return readable ? Mesh57StageCopy::copied : Mesh57StageCopy::unreadable; +} + +// True when note_pipeline keeps the stage copies. The vertex span must be empty, the mesh +// length must be non-zero, the mesh bytes must have been copied, and neither snapshot failed. +// An empty pixel span is kept with the mesh. An unreadable pixel drops the mesh as well. +inline bool mesh57_fixed_stages_kept(bool vertex_empty, bool mesh_length, Mesh57StageCopy pixel, + Mesh57StageCopy mesh) noexcept +{ + if (!vertex_empty || !mesh_length) + return false; + if (pixel == Mesh57StageCopy::unreadable || mesh == Mesh57StageCopy::unreadable) + return false; + return mesh == Mesh57StageCopy::copied; +} + inline const char* mesh57_fixed_pair_reason(const Mesh57PairRecord& record) noexcept { if (record.desc_bytes < 15 * sizeof(std::uint64_t)) @@ -124,9 +151,11 @@ inline const char* mesh57_fixed_pair_reason(const Mesh57PairRecord& record) noex return "slot 57 descriptor has no mesh stage length"; if (!record.mesh_captured) return "slot 57 mesh stage was not captured"; - if (!record.pixel_captured) + if (!record.pixel_captured) { + if (!record.pixel_length) + return "slot 57 pixel stage is absent from the descriptor"; return "slot 57 pixel stage was not captured"; - (void)record.pixel_length; + } return nullptr; } @@ -153,6 +182,17 @@ struct Mesh57DeriveSample { std::uint32_t root_constant_dwords = 0; std::uint32_t root_other = 0; std::uint32_t root_heap = 0; + // First parameters, in order. type 0 is a descriptor table, 1 is 32-bit constants + // (count is the dword count), 2 is a root CBV, 3 is a root SRV, 4 is a root UAV. + static constexpr int root_param_slots = 8; + int root_param_n = 0; + std::uint8_t root_param_type[root_param_slots]{}; + std::uint32_t root_param_count[root_param_slots]{}; + // First slot 55 patch records. tag is the record's first dword and bytes is its size. + static constexpr int patch_slots = 4; + int patch_n = 0; + std::uint32_t patch_tag[patch_slots]{}; + std::uint32_t patch_size[patch_slots]{}; }; // One guest root parameter, without a D3D12 type. type 0 is 32-bit constants and @@ -216,23 +256,80 @@ inline const char* mesh57_root_bind_reason(const Mesh57RootContract& contract) n return nullptr; } -// A slot 55 patch list can reuse a slot 57 mesh when it is empty or every record is a -// blend patch. record bytes are the 0x14c blend record (tag word plus the blend state). -// A tag other than 2, or a size that is not a whole number of records, is not applied. -inline const char* mesh57_slot55_patch_reason(const unsigned char* records, std::size_t bytes) noexcept +// One slot 55 patch record. The creation path stores fixed 0x14c records. The only tag this +// repository applies is 2, the blend descriptor (derived_blend.h). Other tags are named and refused. +struct Mesh57PatchNote { + std::uint32_t tag = 0; + std::uint32_t bytes = 0; +}; + +enum class Mesh57PatchDecision : unsigned { accept = 0, unaligned = 1, other_tag = 2 }; + +struct Mesh57PatchScan { + Mesh57PatchDecision decision = Mesh57PatchDecision::accept; + std::uint32_t other_tag = 0; + int notes = 0; +}; + +// Writes the first cap records. An empty list is accepted. Every whole record must be tag 2. +// A size that is not a whole number of 0x14c records is unaligned; a trailing partial record is +// still noted when cap allows. The first tag that is not 2 is other_tag. +inline Mesh57PatchScan mesh57_scan_slot55_patches(const unsigned char* records, std::size_t bytes, + Mesh57PatchNote* notes, int cap) noexcept { constexpr std::size_t record = 0x14c; + Mesh57PatchScan scan; if (!bytes) - return nullptr; - if (!records || bytes % record) - return "slot 55 patches are not applied"; - for (std::size_t at = 0; at < bytes; at += record) { + return scan; + if (!records || cap < 0) { + scan.decision = Mesh57PatchDecision::unaligned; + return scan; + } + const bool whole = bytes % record == 0; + const std::size_t whole_bytes = whole ? bytes : bytes - (bytes % record); + for (std::size_t at = 0; at < whole_bytes; at += record) { std::uint32_t tag = 0; std::memcpy(&tag, records + at, sizeof(tag)); - if (tag != 2) - return "slot 55 patches are not applied"; + if (tag != 2 && scan.decision == Mesh57PatchDecision::accept) { + scan.decision = Mesh57PatchDecision::other_tag; + scan.other_tag = tag; + } + if (notes && scan.notes < cap) { + notes[scan.notes].tag = tag; + notes[scan.notes].bytes = static_cast(record); + scan.notes += 1; + } } - return nullptr; + if (!whole) { + const std::size_t rest = bytes - whole_bytes; + std::uint32_t tag = 0; + if (rest >= sizeof(tag)) + std::memcpy(&tag, records + whole_bytes, sizeof(tag)); + if (notes && scan.notes < cap) { + notes[scan.notes].tag = tag; + notes[scan.notes].bytes = rest > 0xffffffffu ? 0xffffffffu : static_cast(rest); + scan.notes += 1; + } + scan.decision = Mesh57PatchDecision::unaligned; + } + return scan; +} + +// Stable text for a tag this path does not apply. The caller keeps the buffer it passes. +inline std::size_t mesh57_slot55_tag_reason(std::uint32_t tag, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + const int n = std::snprintf(out, cap, "slot 55 patch tag %u is not applied", tag); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); } struct Mesh57DeriveCensus { @@ -285,18 +382,86 @@ struct Mesh57DeriveCensus { } }; +inline void mesh57_write_root_params(const Mesh57DeriveSample& sample, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return; + out[0] = 0; + if (sample.root_param_n <= 0) { + std::snprintf(out, cap, "-"); + return; + } + std::size_t used = 0; + const int n = sample.root_param_n < Mesh57DeriveSample::root_param_slots + ? sample.root_param_n : Mesh57DeriveSample::root_param_slots; + for (int i = 0; i < n && used + 1 < cap; ++i) { + char piece[16]; + const unsigned type = sample.root_param_type[i]; + const unsigned count = sample.root_param_count[i]; + int wrote = 0; + if (type == 0) + wrote = std::snprintf(piece, sizeof(piece), "t"); + else if (type == 1) + wrote = std::snprintf(piece, sizeof(piece), "c%u", count); + else if (type == 2) + wrote = std::snprintf(piece, sizeof(piece), "cbv"); + else if (type == 3) + wrote = std::snprintf(piece, sizeof(piece), "srv"); + else if (type == 4) + wrote = std::snprintf(piece, sizeof(piece), "uav"); + else + wrote = std::snprintf(piece, sizeof(piece), "p%u", type); + if (wrote <= 0) + break; + const int put = std::snprintf(out + used, cap - used, "%s%s", i ? "," : "", piece); + if (put < 0 || static_cast(put) >= cap - used) { + out[cap - 1] = 0; + return; + } + used += static_cast(put); + } +} + +inline void mesh57_write_patches(const Mesh57DeriveSample& sample, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return; + out[0] = 0; + if (sample.patch_n <= 0) { + std::snprintf(out, cap, "-"); + return; + } + std::size_t used = 0; + const int n = sample.patch_n < Mesh57DeriveSample::patch_slots ? sample.patch_n : Mesh57DeriveSample::patch_slots; + for (int i = 0; i < n && used + 1 < cap; ++i) { + const int put = std::snprintf(out + used, cap - used, "%s%u:%u", i ? "," : "", + sample.patch_tag[i], sample.patch_size[i]); + if (put < 0 || static_cast(put) >= cap - used) { + out[cap - 1] = 0; + return; + } + used += static_cast(put); + } +} + inline std::size_t mesh57_derive_sample_line(const char* reason, const Mesh57DeriveSample& sample, char* out, std::size_t cap) noexcept { if (!out || cap == 0) return 0; + char params[96]; + char patches[80]; + mesh57_write_root_params(sample, params, sizeof(params)); + mesh57_write_patches(sample, patches, sizeof(patches)); const int n = std::snprintf(out, cap, "x2w-render mesh57-derive sample reason=%s path=%d base=%d desc=%u ms=%u ps=%u state_a=%u state_b=%u " - "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d root=%u const=%u other=%u heap=%u", + "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d root=%u const=%u other=%u heap=%u " + "params=%s patches=%s", reason ? reason : "", sample.path, sample.base_path, sample.desc_bytes, sample.mesh_bytes, sample.pixel_bytes, sample.state_a, sample.state_b, sample.vertex_bytes, sample.mesh_length, sample.pixel_length, static_cast(sample.key), sample.list_type, sample.real, - sample.mesh86, sample.root_parameters, sample.root_constant_dwords, sample.root_other, sample.root_heap); + sample.mesh86, sample.root_parameters, sample.root_constant_dwords, sample.root_other, sample.root_heap, + params, patches); if (n < 0) { out[0] = 0; return 0; diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index f2d1c65c31..2aef375dd9 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -531,6 +531,16 @@ x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const Pi sample.pixel_length = mesh57_derive_u32(static_cast(words[6])); sample.mesh_length = mesh57_derive_u32(static_cast(words[14])); } + if (info->path == 55) { + x2w_startup::Mesh57PatchNote notes[x2w_startup::Mesh57DeriveSample::patch_slots]; + const auto scan = x2w_startup::mesh57_scan_slot55_patches( + info->desc.data(), info->desc.size(), notes, x2w_startup::Mesh57DeriveSample::patch_slots); + sample.patch_n = scan.notes; + for (int i = 0; i < scan.notes; ++i) { + sample.patch_tag[i] = notes[i].tag; + sample.patch_size[i] = notes[i].bytes; + } + } const PipelineInfo* root_source = info; for (int depth = 0; root_source && root_source->path == 55 && root_source->base && depth < 8; ++depth) root_source = pipeline_info(root_source->base); @@ -543,6 +553,22 @@ x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const Pi if (const auto* params = root_info(root)) { sample.root_parameters = mesh57_derive_u32(params->size()); for (const auto& parameter : *params) { + unsigned code = 255; + if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + code = 0; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) + code = 1; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_CBV) + code = 2; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_SRV) + code = 3; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_UAV) + code = 4; + if (sample.root_param_n < x2w_startup::Mesh57DeriveSample::root_param_slots) { + sample.root_param_type[sample.root_param_n] = static_cast(code); + sample.root_param_count[sample.root_param_n] = parameter.constants_count; + sample.root_param_n += 1; + } if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { if (sample.root_constant_dwords <= ~std::uint32_t{0} - parameter.constants_count) sample.root_constant_dwords += parameter.constants_count; @@ -567,7 +593,7 @@ void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineI ReleaseSRWLockExclusive(&mesh57_derive_census_lock); if (!first) return; - char line[640]; + char line[1024]; if (x2w_startup::mesh57_derive_sample_line(reason, sample, line, sizeof(line))) log("%s", line); } @@ -587,6 +613,35 @@ void log_mesh57_derive_census() log("%s", line); } +// The census and the pipeline keep the first reason pointer. A formatted tag reason lives in +// this table so that pointer outlives both. Matching is by the characters, not the address. +const char* mesh57_stable_text(const char* text) +{ + static SRWLOCK lock = SRWLOCK_INIT; + struct Kept { char text[80]; }; + static Kept kept[24]; + static int used = 0; + if (!text || !text[0]) + return "slot 55 patch tag is not applied"; + AcquireSRWLockExclusive(&lock); + for (int i = 0; i < used; ++i) { + if (std::strcmp(kept[i].text, text) == 0) { + const char* found = kept[i].text; + ReleaseSRWLockExclusive(&lock); + return found; + } + } + if (used >= 24) { + ReleaseSRWLockExclusive(&lock); + return "slot 55 patch tag is not applied"; + } + std::snprintf(kept[used].text, sizeof(kept[used].text), "%s", text); + const char* stored = kept[used].text; + used += 1; + ReleaseSRWLockExclusive(&lock); + return stored; +} + const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass) { if (!pipeline || pipeline->own().real) @@ -607,9 +662,16 @@ const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass) } if (!base_info || base_info->path != 57) return "pipeline is a derived slot 55"; - if (const char* patch = x2w_startup::mesh57_slot55_patch_reason(info->desc.data(), info->desc.size())) { - info->mesh57_derive_reason = patch; - return patch; + const auto patches = x2w_startup::mesh57_scan_slot55_patches(info->desc.data(), info->desc.size(), nullptr, 0); + if (patches.decision == x2w_startup::Mesh57PatchDecision::unaligned) { + info->mesh57_derive_reason = "slot 55 patches are not applied"; + return info->mesh57_derive_reason; + } + if (patches.decision == x2w_startup::Mesh57PatchDecision::other_tag) { + char named[80]; + x2w_startup::mesh57_slot55_tag_reason(patches.other_tag, named, sizeof(named)); + info->mesh57_derive_reason = mesh57_stable_text(named); + return info->mesh57_derive_reason; } D3D12_BLEND_DESC blend{}; std::size_t where = 0; diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp index 73ed5094c3..4683fc634a 100644 --- a/tests/mesh57_derive_alloc_check.cpp +++ b/tests/mesh57_derive_alloc_check.cpp @@ -127,6 +127,22 @@ int main() if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), "slot 57 pixel stage was not captured") != 0) return fail("pixel stage"); + pair.pixel_length = 0; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 pixel stage is absent from the descriptor") != 0) + return fail("absent pixel span"); + // The descriptor words are zero, so the copy is skipped and the mesh bytes stay. + // A non-zero span that cannot be read fails the snapshot and drops both stages. + if (x2w_startup::mesh57_stage_copy(0, 0, false) != x2w_startup::Mesh57StageCopy::empty || + !x2w_startup::mesh57_fixed_stages_kept(true, true, x2w_startup::Mesh57StageCopy::empty, + x2w_startup::Mesh57StageCopy::copied)) + return fail("empty pixel keeps the mesh"); + if (x2w_startup::mesh57_stage_copy(0x1000, 1408, false) != x2w_startup::Mesh57StageCopy::unreadable || + x2w_startup::mesh57_fixed_stages_kept(true, true, x2w_startup::Mesh57StageCopy::unreadable, + x2w_startup::Mesh57StageCopy::copied)) + return fail("unreadable pixel drops the mesh"); + if (x2w_startup::mesh57_stage_copy(0, 1408, true) != x2w_startup::Mesh57StageCopy::copied) + return fail("readable pixel is copied"); x2w_startup::Mesh57DeriveCensus census; x2w_startup::Mesh57DeriveSample slot86; @@ -161,8 +177,31 @@ int main() !std::strstr(sample, "reason=pipeline is slot 86") || !std::strstr(sample, "path=86") || !std::strstr(sample, "desc=512") || !std::strstr(sample, "root=0") || !std::strstr(sample, "const=0") || !std::strstr(sample, "other=0") || !std::strstr(sample, "heap=0") || + !std::strstr(sample, "params=-") || !std::strstr(sample, "patches=-") || std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) return fail("sample"); + x2w_startup::Mesh57DeriveSample typed; + typed.path = 57; + typed.root_parameters = 5; + typed.root_constant_dwords = 1; + typed.root_other = 4; + typed.root_heap = 1024; + typed.root_param_n = 5; + const unsigned typed_codes[] = {0u, 1u, 3u, 2u, 4u}; + const unsigned typed_counts[] = {0u, 1u, 0u, 0u, 0u}; + for (int i = 0; i < 5; ++i) { + typed.root_param_type[i] = static_cast(typed_codes[i]); + typed.root_param_count[i] = typed_counts[i]; + } + typed.patch_n = 1; + typed.patch_tag[0] = 3; + typed.patch_size[0] = 0x14c; + char typed_line[640]; + if (!x2w_startup::mesh57_derive_sample_line("derived mesh guest root is heap indexed", typed, typed_line, + sizeof(typed_line)) || + !std::strstr(typed_line, "params=t,c1,srv,cbv,uav") || !std::strstr(typed_line, "patches=3:332") || + !std::strstr(typed_line, "root=5") || !std::strstr(typed_line, "heap=1024")) + return fail("parameter and patch sample"); x2w_startup::Mesh57RootParameterView one; one.type = 0; one.constants = 1; @@ -204,14 +243,36 @@ int main() std::memset(blend_record, 0, sizeof(blend_record)); const std::uint32_t blend_tag = 2; std::memcpy(blend_record, &blend_tag, sizeof(blend_tag)); - if (x2w_startup::mesh57_slot55_patch_reason(nullptr, 0) || - x2w_startup::mesh57_slot55_patch_reason(blend_record, sizeof(blend_record))) + x2w_startup::Mesh57PatchNote notes[4]; + const auto blend_only = x2w_startup::mesh57_scan_slot55_patches(nullptr, 0, notes, 4); + const auto one_blend = x2w_startup::mesh57_scan_slot55_patches(blend_record, sizeof(blend_record), notes, 4); + if (blend_only.decision != x2w_startup::Mesh57PatchDecision::accept || + one_blend.decision != x2w_startup::Mesh57PatchDecision::accept || one_blend.notes != 1 || + notes[0].tag != 2 || notes[0].bytes != 0x14c) return fail("blend patch"); + unsigned char mixed[0x14c * 2]; + std::memset(mixed, 0, sizeof(mixed)); + std::memcpy(mixed, blend_record, sizeof(blend_record)); + const std::uint32_t other_tag = 3; + std::memcpy(mixed + sizeof(blend_record), &other_tag, sizeof(other_tag)); + const auto mixed_scan = x2w_startup::mesh57_scan_slot55_patches(mixed, sizeof(mixed), notes, 4); + char tag_reason[80]; + if (mixed_scan.decision != x2w_startup::Mesh57PatchDecision::other_tag || mixed_scan.other_tag != 3 || + mixed_scan.notes != 2 || notes[0].tag != 2 || notes[1].tag != 3 || notes[1].bytes != 0x14c || + !x2w_startup::mesh57_slot55_tag_reason(mixed_scan.other_tag, tag_reason, sizeof(tag_reason)) || + std::strcmp(tag_reason, "slot 55 patch tag 3 is not applied") != 0) + return fail("named patch tag"); + char tag_reason_copy[80]; + x2w_startup::mesh57_slot55_tag_reason(3, tag_reason_copy, sizeof(tag_reason_copy)); + if (&tag_reason[0] == &tag_reason_copy[0] || std::strcmp(tag_reason, tag_reason_copy) != 0 || + !census.note(tag_reason, slot86) || census.note(tag_reason_copy, slot86)) + return fail("tag reason text is one reason"); blend_record[0] = 1; - if (std::strcmp(x2w_startup::mesh57_slot55_patch_reason(blend_record, sizeof(blend_record)), - "slot 55 patches are not applied") != 0 || - std::strcmp(x2w_startup::mesh57_slot55_patch_reason(blend_record, 4), - "slot 55 patches are not applied") != 0) + const auto unknown = x2w_startup::mesh57_scan_slot55_patches(blend_record, sizeof(blend_record), notes, 4); + const auto short_list = x2w_startup::mesh57_scan_slot55_patches(blend_record, 4, notes, 4); + if (unknown.decision != x2w_startup::Mesh57PatchDecision::other_tag || unknown.other_tag != 1 || + short_list.decision != x2w_startup::Mesh57PatchDecision::unaligned || short_list.notes != 1 || + notes[0].bytes != 4) return fail("unknown patch"); if (!census.note("forwarded", slot86) || x2w_startup::mesh57_derive_forwarded(census) != 1) return fail("forwarded count");