diff --git a/docs/fspx.md b/docs/fspx.md index 6fa4a4c8db..76c246277e 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -236,8 +236,9 @@ and `RSRC2`). **Slot 57 (`DeserializeGraphicsPipelineStateX`, graphics FSPX).** At `game_scarlett_master.exe+0x2477578`, the retail title calls device slot 57 (`+0x1c8`) with `IID_ID3D12PipelineState` (`{765a30f3-f624-4c6f-a828-ace948622445}`) and a -104-byte description (`+0x00..+0x60`) populated from the zlib-compressed pipeline library in `shaders.rpf` -([shader_library.md](shader_library.md): 25,471 graphics records + 2,693 compute records): +description populated from the zlib-compressed pipeline library in `shaders.rpf`. Its first two stage blocks +and the preceding fields occupy the 104-byte prefix (`+0x00..+0x60`) shown below. The library contains +25,471 graphics records and 2,693 compute records. [Pipeline library layout](shader_library.md) | Offset | Field | Measured layout | |---|---|---| @@ -254,9 +255,14 @@ title calls device slot 57 (`+0x1c8`) with `IID_ID3D12PipelineState` (`{765a30f3 2. Record 8917 (`f7808a66fb6b97c1`): state 388 B (`0x4005d808`), pipeline blob 188 B (`0x542385d2`), `ps` prog 844 (768 B, SHA-256 `947014e8b0771be5...`), `vs` prog 845 (320 B, SHA-256 `a2dce0214f82c742...`). 3. Record 12511 (`e750e10eacb97b9c`): state 380 B (`0x4005d808`), pipeline blob 188 B (`0xfb724939`), no `ps`, `vs` prog 5636 (320 B, SHA-256 `f6bfddbad6aef3cd...`). In the library, the 448/768 B program at `+0x28` is the pixel shader (`ps`, paired with the 208 B stage blob) and the - 384/320 B program at `+0x48` is the vertex shader (`vs`, paired with the 752 B stage blob). Programs are looked up by - `sha256(program bytes)` in `/fspx_gfx/index.json` (`ShaderLibrary::fspx_gfx_size()`, separate from - `fspx_size()`), and their `stage` (`"vs"` / `"ps"` / `"ms"`) is taken from the index entry rather than the blob slot. + 384/320 B program at `+0x48` is the vertex shader (`vs`, paired with the 752 B stage blob). +- The Vulkan factory reads all seven stage blocks of the 0x108-byte description. A stage record's DXBC HASH + selects its source container through `native_hashes.txt`. A stage without a matching container identity can + resolve through the SHA-256 of its complete program in `/fspx_gfx/index.json`. The indexed stage + identifies VS, PS or MS. A digest shared by different stages cannot select one from code alone. If a source + container fails validation or its PSO is refused, the factory can retry with indexed code for the same + stage, retaining the decoded state, input layout and root signature. `--trace-d3d12` records the number of + catalog and kind-6 stages submitted to the Vulkan factory and its HRESULT. [Build and coverage](shader_library.md) - **Measured `pipeline blob` layout (188 B = `0xbc`):** - `+0x00`: u32 per-PSO checksum (`0xea6f6e56` / `0x542385d2` / `0xfb724939`) - `+0x04`: u32 `0x1000` (constant across 2,642 blobs), `+0x08`: `0`, `+0x0c`: `1` diff --git a/docs/shader_library.md b/docs/shader_library.md index 3ef944a528..bb0a7fd18a 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -176,7 +176,32 @@ library through DirectStorage zlib requests and passes each compute record's fou `DeserializeComputePipelineStateX`, as kinds 0, 1, 6 and 7, so the code key is the program's bytes as the table gives them and the state key is the record's state blob. The step is redone as a whole when `shaders.rpf`, the tools, `llvm-mc`, the wave64 mode or the flags change (`library_build.json`, written last), and a clash of both keys between -different modules fails it, as for the FSPX step. Graphics pipelines are not translated by the build. +different modules fails it, as for the FSPX step. + +For device slot 57 the same build unpacks the PS, VS and MS selections into `/shaders/fspx_gfx`. +It disassembles the pipeline-specific kind-6 bytes and translates them into `/shaders/spirv/fspx_gfx`. +Each published row names its stage and the SHA-256 of the entire kind-6 program, including its prologue. The +source container supplies signatures and PSV0 when available. Run the usual `make_game.py --stages shaders` +with the same game, work folder and translation options to add this index to an existing workspace. Compute +and graphics have separate build markers. The graphics marker also records the output index digest and the +number of extracted and translated programs. A missing module or a truncated index triggers a graphics rebuild. + +In the original build shell, use the paths for that workspace and any adapter options used for its first +translation. The two CTests draw with hand-built native descriptions and check the GPU pixels. + +```powershell +python -I make_game.py --game $game --work $work --out $port --stages shaders +ctest --test-dir $build -C RelWithDebInfo -R '^xbox_native_fspx_(draw|mesh)$' --output-on-failure +``` + +On 1.0.2.1 the 25,471 graphics records reference 18,837 distinct programs in the three identified stages. +In both native-wave64 and wave64-emulation builds, 9,671 of 9,996 PS, 1,342 of 1,343 VS and 7,480 of 7,498 MS +translated and passed `spirv-val`. Every published key matched the complete extracted program. Of the identified +programs, 18,829 have a 36-byte prologue and eight have the 24-byte two-carrier form. Looking up all stages +by raw code alone covered 24,983 records. The per-record layout digests linked all stages to the DXBC catalog +for 25,450 records. Two records also name the unidentified slot-6 program. A record +with all of its stage links still needs a valid root signature, fixed-function state and a device that supports +its pipeline before it can draw. [Slot 57 and native shader lookup](fspx.md) ### Resuming a compute-only batch on Linux diff --git a/make_game.py b/make_game.py index 3eb0899458..9804f24c3c 100644 --- a/make_game.py +++ b/make_game.py @@ -71,7 +71,7 @@ sys.path.insert(0, TOOLS) from mc_command import install_hint as mc_install_hint, mc_command # noqa: E402 import leonida_tui # noqa: E402 -from shader_stage_manifest import shader_stems # noqa: E402 +from shader_stage_manifest import shader_stages, shader_stems # noqa: E402 from replace_retry import replace as replace_retry # noqa: E402 from stale_build import newer_sources # noqa: E402 @@ -1463,7 +1463,7 @@ def fspx_shaders(game: str, work: str, mc_signature: str, emulate: bool = False, def library_settings(archive: str, mc_signature: str, emulate: bool, fallbacks: tuple[str, ...]) -> str: - """What the pipeline library's compute translations depend on, as one line: shaders.rpf, the unpacking and + """What the pipeline library's translations depend on, as one line: shaders.rpf, the unpacking and translating tools, llvm-mc, the wave64 mode and the fallback flags.""" return json.dumps({"archive": file_sha256(archive), "tools": sources_digest(TOOLS, LIBRARY_TOOLS), "translator": translation_sources_digest(), "llvm_mc": mc_signature, @@ -1472,31 +1472,38 @@ def library_settings(archive: str, mc_signature: str, emulate: bool, fallbacks: def library_shaders(game: str, work: str, mc_signature: str, jobs: int, emulate: bool = False, fallbacks: tuple[str, ...] = ()) -> None: - """The compute pipelines of the pipeline library in shaders.rpf (docs/shader_library.md). The executable reads - the library through DirectStorage and creates each compute pipeline with Xbox device slot 67 - (DeserializeComputePipelineStateX), passing the record's four parts as FSPX kinds 0, 1, 6 and 7 (docs/fspx.md). - tools/shader_library.py unpacks the compute programs with their kind-0 state into /shaders/library, and - translate() runs rdna2spirv.py across jobs processes into /shaders/spirv/library, where the runtime's - shader library finds them by fspx_code_sha256 and fspx_state_sha256 as it finds the FidelityFX DLL's. Graphics - pipelines are not translated here. The game's own shaders neither feed nor depend on this step, apart from the - carve that names each program's source container (the translator reads its signatures). - - The step runs whole. Reuse requires the translation index, its named modules and a matching library_build.json - (library_settings).""" + """Build the pipeline-library programs used by Xbox slots 67 (compute) and 57 (graphics). + Each directory has its own index and build marker so an existing compute translation can be reused.""" archive = os.path.join(game, LIBRARY_ARCHIVE) - unpacked = os.path.join(work, "shaders", "library") - spirv = os.path.join(work, "shaders", "spirv", "library") + settings = library_settings(archive, mc_signature, emulate, fallbacks) if os.path.isfile(archive) else None + if settings is None: + log(f"shaders: no {LIBRARY_ARCHIVE} in the game folder, so no pipeline library to translate") + for folder, stages in (("library", ("cs",)), ("fspx_gfx", ("ps", "vs", "ms"))): + translate_library_stages(archive, work, folder, stages, settings, jobs, emulate, fallbacks) + + +def translate_library_stages(archive: str, work: str, folder_name: str, stages: tuple[str, ...], + settings: str | None, jobs: int, emulate: bool, fallbacks: tuple[str, ...]) -> None: + unpacked = os.path.join(work, "shaders", folder_name) + spirv = os.path.join(work, "shaders", "spirv", folder_name) translated = os.path.join(spirv, "index.json") shard_plan = os.path.join(spirv, SHARD_PLAN) settings_file = os.path.join(spirv, "library_build.json") - if not os.path.isfile(archive): + if settings is None: drop(translated, settings_file, shard_plan) - log(f"shaders: no {LIBRARY_ARCHIVE} in the game folder, so no pipeline library to translate") return - settings = library_settings(archive, mc_signature, emulate, fallbacks) - if read_shader_setting(settings_file) == settings and fspx_cache_complete(spirv): - return - log(f"shaders: unpacking and translating the compute pipelines of the pipeline library in {LIBRARY_ARCHIVE}") + graphics = folder_name == "fspx_gfx" + saved = read_shader_setting(settings_file) + if saved: + if graphics: + if saved == graphics_library_stamp(unpacked, spirv, settings): + report_graphics_library(saved) + return + elif saved == settings and (fspx_cache_complete(spirv) or + (read_shader_setting(translated) == "{}" and empty_library_selection(unpacked))): + return + stage_list = ",".join(stages) + log(f"shaders: unpacking and translating pipeline library programs ({stage_list}) in {LIBRARY_ARCHIVE}") drop(translated, settings_file, shard_plan) # A program that no longer translates or lost its carve container must not keep outputs from the run before. for folder, suffixes in ((unpacked, (".dxbc",)), @@ -1509,14 +1516,60 @@ def library_shaders(game: str, work: str, mc_signature: str, jobs: int, emulate: if entry.name.endswith(suffixes) and entry.is_file(follow_symlinks=False): os.unlink(entry.path) carve = os.path.join(work, "shaders", "dxbc") - py("shader_library.py", archive, "--out", unpacked, "--stages", "cs", "--disasm", "--jobs", str(jobs), + py("shader_library.py", archive, "--out", unpacked, "--stages", stage_list, "--disasm", "--jobs", str(jobs), *(["--carve", carve] if os.path.isdir(carve) else [])) - translate(os.path.join(unpacked, "disasm"), spirv, jobs, emulate=emulate, fallbacks=fallbacks) + if empty_library_selection(unpacked): + # A library with only one pipeline type has a valid, empty selection for the other. + os.makedirs(spirv, exist_ok=True) + with open(translated, "w", encoding="utf-8", newline="\n") as f: + f.write("{}\n") + else: + translate(os.path.join(unpacked, "disasm"), spirv, jobs, emulate=emulate, fallbacks=fallbacks) verify_fspx_key_clash(spirv, translated, "pipeline library") + if graphics: + settings = graphics_library_stamp(unpacked, spirv, settings) + if settings is None: + drop(translated) + fail("shaders: the graphics pipeline library index has missing modules or unusable stage/hash metadata") + report_graphics_library(settings) with open(settings_file, "w", encoding="utf-8", newline="\n") as f: f.write(settings + "\n") +def empty_library_selection(unpacked: str) -> bool: + try: + return not shader_stems(os.path.join(unpacked, "index.json"), "file", ".dxbc") + except (OSError, ValueError): + return False + + +def graphics_library_stamp(unpacked: str, spirv: str, settings: str) -> str | None: + """Bind the build marker to the published index, including its coverage when a translation is refused.""" + try: + extracted = shader_stages(os.path.join(unpacked, "index.json"), "file", ".dxbc") + with open(os.path.join(spirv, "index.json"), "rb") as f: + data = f.read() + index = json.loads(data) + except (OSError, ValueError): + return None + if not isinstance(index, dict) or (extracted and not index): + return None + for name, meta in index.items(): + stage = extracted.get(name) + if (stage not in ("ps", "vs", "ms") or not isinstance(meta, dict) or meta.get("stage") != stage + or not isinstance(meta.get("fspx_code_sha256"), str) + or not re.fullmatch(r"[0-9a-f]{64}", meta["fspx_code_sha256"]) + or not os.path.isfile(os.path.join(spirv, name + ".spv"))): + return None + return json.dumps({"inputs": json.loads(settings), "index_sha256": hashlib.sha256(data).hexdigest(), + "translated": len(index), "programs": len(extracted)}, sort_keys=True) + + +def report_graphics_library(stamp: str) -> None: + result = json.loads(stamp) + log(f"shaders: {result['translated']} of {result['programs']} graphics pipeline library programs translated") + + def verify_fspx_key_clash(spirv: str, translated: str, label: str) -> None: """Reject an unreadable translation index or one whose kind-6 and kind-0 keys pick between different modules.""" try: diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 48c8af3602..286dbfe32d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3010,6 +3010,8 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_translated_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) add_test(NAME xbox_native_base_draw COMMAND d3d12_translated_draw_test --native-pso) + add_test(NAME xbox_native_fspx_draw COMMAND d3d12_translated_draw_test --native-fspx) + set_tests_properties(xbox_native_fspx_draw PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME xbox_derived_mask_zero COMMAND d3d12_translated_draw_test --derived-zero) add_test(NAME xbox_derived_mask_restore COMMAND d3d12_translated_draw_test --derived-restore) @@ -3736,7 +3738,8 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) - set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME xbox_native_fspx_mesh COMMAND d3d12_mesh_test --native-fspx) + set_tests_properties(d3d12_mesh xbox_native_fspx_mesh PROPERTIES SKIP_RETURN_CODE 77) else() message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") endif() diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 12494d201d..fe1f17792d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7222,7 +7222,7 @@ class PipelineState final VkShaderStageFlagBits bit; const D3D12_SHADER_BYTECODE& code; const leonida::ShaderEntry* entry = nullptr; - std::vector fssm; + std::vector program_bytes; std::vector words; }; Stage stages[3] = {mesh ? Stage{"ms", VK_SHADER_STAGE_MESH_BIT_EXT, *ms} @@ -7266,10 +7266,10 @@ class PipelineState final if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only const std::span raw_bytes{ static_cast(stage.code.pShaderBytecode), stage.code.BytecodeLength}; - stage.fssm = leonida::fssm_program(raw_bytes); + stage.program_bytes = leonida::fssm_program(raw_bytes); const bool vertex = stage.bit == VK_SHADER_STAGE_VERTEX_BIT; - if (!stage.fssm.empty()) { - const std::string hash = leonida::sha256_hex(stage.fssm); + if (!stage.program_bytes.empty()) { + const std::string hash = leonida::sha256_hex(stage.program_bytes); // Containers with the same program can differ in their input signature or bindings: a VS must have its // inputs fed by this input layout (else the layout check below reports it). stage.entry = pick_entry(library->candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { @@ -7298,6 +7298,7 @@ class PipelineState final stage.name, hash.c_str(), raw_bytes.size()); return stub_or(E_INVALIDARG, "graphics"); } + if (stage.entry->uses_code_base) stage.program_bytes.assign(raw_bytes.begin(), raw_bytes.end()); } else { log_once("shader bytecode holds no FSSM or FSPX program; bytes", int(stage.code.BytecodeLength)); return E_INVALIDARG; @@ -7796,9 +7797,9 @@ class PipelineState final if (code_stage) { VkDeviceSize offset = 0; - if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + offset, code_stage->fssm.data(), code_stage->fssm.size()); - code_bytes_ = code_stage->fssm.size(); + if (!device_.arena_allocate(code_stage->program_bytes.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; + std::memcpy(device_.arena.mapped + offset, code_stage->program_bytes.data(), code_stage->program_bytes.size()); + code_bytes_ = code_stage->program_bytes.size(); code_base_ = offset; graphics_.code_base = offset; } @@ -10321,7 +10322,7 @@ class Device final HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { const auto* shaders = state_.library(); if (!shaders) return E_NOTIMPL; - return state_.native_graphics.create(shaders->directory(), desc, out, [&](const auto& pc, const auto& mesh, const auto& containers) { + return state_.native_graphics.create(*shaders, desc, out, [&](const auto& pc, const auto& mesh, const auto& containers) { return shared_native_graphics(pc, mesh, containers, iid, out); }); } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 60d7c62f30..d7f6ab4340 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -3896,9 +3896,8 @@ std::uint64_t proxy_create_committed_resource(DeviceProxy* self, std::uint64_t a } // Xbox slot 57 through the factory of the device behind the proxy (set_device_native_graphics_factory), which -// takes the whole description. E_NOTIMPL (no factory, or one that cannot build this description) sends the call -// to proxy_create_graphics_pipeline_from_native_code below. -HRESULT proxy_create_native_graphics(DeviceProxy* self, const void* raw, REFIID riid, void** out) { +// takes all seven stage blocks. The legacy description below can carry only the first two. +HRESULT proxy_create_native_graphics(DeviceProxy* self, const void* raw, REFIID riid, void** out, bool& legacy_shape) { namespace np = leonida::native_pso; if (!out) return E_POINTER; *out = nullptr; @@ -3906,6 +3905,9 @@ HRESULT proxy_create_native_graphics(DeviceProxy* self, const void* raw, REFIID if (!accessible_range(raw, sizeof(np::GraphicsDesc), false)) return E_INVALIDARG; np::GraphicsDesc desc{}; std::memcpy(&desc, raw, sizeof(desc)); + legacy_shape = std::none_of(desc.stages + 2, std::end(desc.stages), [](const np::StageBlock& stage) { + return stage.code.size || stage.records.size; + }); const auto readable_pair = [](const np::Pair& pair) { const auto state = np::pair_state(pair); return state == np::PairState::absent || @@ -4993,10 +4995,11 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 note_slot(57); log_xbox_route_once(57, "DeserializeGraphicsPipelineStateX", a1, a2, a3, a4, a5); HRESULT hr = E_NOTIMPL; + bool legacy_shape = true; if (riid && self->native_graphics) hr = proxy_create_native_graphics(self, reinterpret_cast(a1), *riid, - reinterpret_cast(a3)); - if (hr == E_NOTIMPL) + reinterpret_cast(a3), legacy_shape); + if (hr == E_NOTIMPL && legacy_shape) hr = proxy_create_graphics_pipeline_from_native_code( self, reinterpret_cast(a1), riid, reinterpret_cast(a3)); return hr_to_u64(d3d12_trace::result("XboxID3D12Device::CreateNativeGraphicsPipelineState", hr)); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 7e4660953b..eb4abc475f 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -13,8 +13,8 @@ // boot. Only for a caller in a guest-mapped image (set_console_caller, below); a host caller reaches the // PC CreateMetaCommand. // slot 57 the native graphics pipeline state (desc, iid, out). The factory of set_device_native_graphics_factory -// (below) is asked first with the whole 0x108-byte description (leonida::native_pso::GraphicsDesc); when -// it answers E_NOTIMPL (none set, no catalogue, or a plan it cannot build) the call goes on as +// (below) is asked first with the whole 0x108-byte description (leonida::native_pso::GraphicsDesc). +// E_NOTIMPL can try the two-block path when all later blocks are empty. Without a factory, the path is // DeserializeGraphicsPipelineStateX(desc, iid, out): converts the Xbox 0x68-byte native graphics PSO // description (+0x00 root signature, +0x08/+0x10 state blob, +0x18/+0x20 pipeline input-layout blob, // +0x28/+0x30 and +0x48/+0x50 bare RDNA2 programs, +0x38/+0x40 and +0x58/+0x60 kind-2 stage blobs) to diff --git a/runtime/shims/d3d12_xs_native_pso.h b/runtime/shims/d3d12_xs_native_pso.h index ba8537c5fc..bff6d40841 100644 --- a/runtime/shims/d3d12_xs_native_pso.h +++ b/runtime/shims/d3d12_xs_native_pso.h @@ -10,13 +10,16 @@ // stage bytecode handed on is read from the user's own carved DXBC containers, not from the description. // // Xbox native graphics pipeline state, adapted from enx/leonida's slot-57 implementation. -// The state and stage resolution are in native_pso.h. All stage bytecode handed to D3D12 -// comes from the user's carved DXBC containers and is translated by the normal Vulkan PSO path. +// The state and stage resolution are in native_pso.h. The Vulkan PSO path can use either the +// user's carved DXBC container or the pipeline library's indexed native program. #include "../src/native_pso.h" +#include "d3d12_trace.h" #include "d3d12_xs_pso_stream.h" #include "../src/shader_library.h" +#include "../src/title_texture_memory.h" #include +#include #include #include #include @@ -142,49 +145,58 @@ inline void build_stream(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHA class NativeGraphicsPipelines { public: template - HRESULT create(const std::filesystem::path& folder, const leonida::native_pso::GraphicsDesc& desc, + HRESULT create(const leonida::ShaderLibrary& library, const leonida::native_pso::GraphicsDesc& desc, void** out, Create&& create_pipeline) { using namespace native_pipeline_detail; *out = nullptr; try { + const auto& folder = library.directory(); std::call_once(load_, [&] { std::ifstream file(folder / L"native_hashes.txt", std::ios::binary); if (!file) { - std::fprintf(stderr, "[rt] d3d12_xs: slot 57 needs native_hashes.txt from the shaders stage\n"); + std::fprintf(stderr, "[rt] d3d12_xs: slot 57 has no native_hashes.txt; checking indexed native programs\n"); return; } const std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; std::string error; if (!catalog_.parse(text, &error)) std::fprintf(stderr, "[rt] d3d12_xs: slot 57: %s\n", error.c_str()); }); - const auto plan = np::plan(desc, catalog_); - if (plan.status == np::PlanStatus::malformed) return E_INVALIDARG; - if (plan.status != np::PlanStatus::ok) return E_NOTIMPL; - - D3D12_GRAPHICS_PIPELINE_STATE_DESC pc{}; - pc.pRootSignature = static_cast(const_cast(desc.root_signature)); - fill_fixed_state(plan.state, pc); - std::vector elements; - for (const auto& e : plan.state.elements) { - elements.push_back({e.name.c_str(), e.semantic_index, static_cast(e.format), e.input_slot, - e.aligned_byte_offset, static_cast(e.classification), - e.step_rate}); + bool unreadable = false; + const auto code_stage = [&](const np::Pair& code) -> std::string_view { + if (!library.fspx_gfx_size()) return {}; + if (!leonida::texture_memory_readable(reinterpret_cast(code.data), code.size)) { + unreadable = true; + return {}; + } + const auto bytes = np::bytes(code); + if (!leonida::fspx_bare_program(bytes)) return {}; + const auto* entry = library.find_fspx_by_code(leonida::sha256_hex(bytes)); + return entry ? std::string_view(entry->stage) : std::string_view{}; + }; + auto plan = np::plan(desc, catalog_, code_stage); + if (plan.status != np::PlanStatus::ok) { + if (rt::d3d12_trace::enabled()) + std::fprintf(stderr, "[d3d12-trace] slot 57 block %zu: %s\n", plan.failed_block, + unreadable ? "native code range unreadable" : plan.reason); + return unreadable || plan.status == np::PlanStatus::malformed || plan.status == np::PlanStatus::ambiguous + ? E_INVALIDARG : E_NOTIMPL; } - pc.InputLayout = {elements.data(), static_cast(elements.size())}; - std::array code; - D3D12_SHADER_BYTECODE mesh{}; - for (const auto& stage : plan.stages) { - auto& bytes = code[stage.block]; - bytes = container(folder, *stage.shader); - if (!bytes) return E_INVALIDARG; - const D3D12_SHADER_BYTECODE view{bytes->data(), bytes->size()}; - if (stage.shader->stage == "vs") pc.VS = view; - else if (stage.shader->stage == "ps") pc.PS = view; - else if (stage.shader->stage == "gs") pc.GS = view; - else mesh = view; // plan() admits only VS/PS/GS or MS/PS. + const HRESULT result = build(folder, desc, plan, create_pipeline); + if ((result != E_INVALIDARG && result != E_NOTIMPL && result != E_FAIL) || !library.fspx_gfx_size()) + return result; + + // A catalog entry can name a stale container, or its general translation can be refused. + // Retry using the indexed pipeline-specific bytes for those same stages. Preserve the other bindings. + bool changed = false; + for (auto& stage : plan.stages) { + const auto& code = desc.stages[stage.block].code; + if (stage.container && np::pair_state(code) == np::PairState::present && code_stage(code) == stage.stage) { + stage.container = nullptr; + changed = true; + } } - return create_pipeline(pc, mesh, code); + return changed ? build(folder, desc, plan, create_pipeline) : result; } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; } catch (const std::exception&) { @@ -194,6 +206,49 @@ class NativeGraphicsPipelines { private: using Container = std::shared_ptr>; + template + HRESULT build(const std::filesystem::path& folder, const leonida::native_pso::GraphicsDesc& desc, + const leonida::native_pso::Plan& plan, Create& create_pipeline) { + using namespace native_pipeline_detail; + D3D12_GRAPHICS_PIPELINE_STATE_DESC pc{}; + pc.pRootSignature = static_cast(const_cast(desc.root_signature)); + fill_fixed_state(plan.state, pc); + std::vector elements; + for (const auto& e : plan.state.elements) { + elements.push_back({e.name.c_str(), e.semantic_index, static_cast(e.format), e.input_slot, + e.aligned_byte_offset, static_cast(e.classification), + e.step_rate}); + } + pc.InputLayout = {elements.data(), static_cast(elements.size())}; + + std::array code; + D3D12_SHADER_BYTECODE mesh{}; + for (const auto& stage : plan.stages) { + auto& bytes = code[stage.block]; + if (stage.container) { + bytes = container(folder, *stage.container); + if (!bytes) return E_INVALIDARG; + } else { + const auto raw = np::bytes(desc.stages[stage.block].code); + bytes = std::make_shared>(raw.begin(), raw.end()); + } + const D3D12_SHADER_BYTECODE view{bytes->data(), bytes->size()}; + if (stage.stage == "vs") pc.VS = view; + else if (stage.stage == "ps") pc.PS = view; + else if (stage.stage == "gs") pc.GS = view; + else mesh = view; // plan() admits only VS/PS/GS or MS/PS. + } + const HRESULT result = create_pipeline(pc, mesh, code); + if (rt::d3d12_trace::enabled()) { + const auto raw = std::count_if(plan.stages.begin(), plan.stages.end(), [](const np::PlannedStage& s) { + return !s.container; + }); + std::fprintf(stderr, "[d3d12-trace] slot 57 stage sources: catalog=%zu kind6=%zu hr=0x%08lx\n", + plan.stages.size() - raw, static_cast(raw), static_cast(result)); + } + return result; + } + Container container(const std::filesystem::path& folder, const leonida::native_pso::ShaderRef& ref) { { std::lock_guard lock(mutex_); diff --git a/runtime/src/native_pso.h b/runtime/src/native_pso.h index 8982c701ac..6bcbec2dba 100644 --- a/runtime/src/native_pso.h +++ b/runtime/src/native_pso.h @@ -254,13 +254,14 @@ class HashMap { struct PlannedStage { std::size_t block = 0; - const ShaderRef* shader = nullptr; + std::string_view stage; + const ShaderRef* container = nullptr; // otherwise use the block's indexed kind-6 program }; enum class PlanStatus { ok, malformed, // a pair is malformed or blob B does not decode - missing, // a stage has no records, or its digest names no translated container + missing, // neither its records nor its code identify a translated stage ambiguous, // a stage's records name two different containers unsupported, // a stage kind this path does not build (hs, ds, cs), two of one kind, or no VS/MS }; @@ -273,14 +274,15 @@ struct Plan { const char* reason = ""; // why a description is malformed bool mesh = false; // an MS stage: the pipeline goes through a pipeline state stream - const ShaderRef* stage(std::string_view name) const { + bool has_stage(std::string_view name) const { for (const PlannedStage& s : stages) - if (s.shader->stage == name) return s.shader; - return nullptr; + if (s.stage == name) return true; + return false; } }; -inline Plan plan(const GraphicsDesc& desc, const HashMap& map) { +template +inline Plan plan(const GraphicsDesc& desc, const HashMap& map, CodeStage&& code_stage) { Plan p; if (pair_state(desc.state_a) == PairState::malformed) { p.reason = "blob A pair malformed"; @@ -302,36 +304,40 @@ inline Plan plan(const GraphicsDesc& desc, const HashMap& map) { return p; } if (code == PairState::absent && records == PairState::absent) continue; - if (records != PairState::present) { // code without records: nothing names its container - p.status = PlanStatus::missing; - return p; - } const ShaderRef* found = nullptr; for (const Digest& d : record_digests(bytes(block.records))) { const ShaderRef* ref = map.find(d); if (!ref) continue; if (found && found != ref) { p.status = PlanStatus::ambiguous; + p.reason = "stage records name two different shader containers"; p.failed_block = k; return p; } found = ref; } p.failed_block = k; - if (!found) { + // Prefer the container named by the records. A bare program can also name its stage + // by the exact kind-6 digest published in fspx_gfx/index.json. + std::string_view s; + if (found) s = found->stage; + else if (code == PairState::present) s = code_stage(block.code); + if (s.empty()) { p.status = PlanStatus::missing; + p.reason = "no matching DXBC identity or indexed native program"; return p; } - const std::string& s = found->stage; - if (!(s == "vs" || s == "ps" || s == "gs" || s == "ms") || p.stage(s)) { + if (!(s == "vs" || s == "ps" || s == "gs" || s == "ms") || p.has_stage(s)) { p.status = PlanStatus::unsupported; + p.reason = "unsupported or duplicate graphics stage"; return p; } - p.stages.push_back({k, found}); + p.stages.push_back({k, s, found}); } - const bool vs = p.stage("vs"), ms = p.stage("ms"); - if (vs == ms || (ms && p.stage("gs"))) { + const bool vs = p.has_stage("vs"), ms = p.has_stage("ms"); + if (vs == ms || (ms && p.has_stage("gs"))) { p.status = PlanStatus::unsupported; + p.reason = "invalid vertex, mesh or geometry stage combination"; return p; } p.mesh = ms; diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index a359287cb1..ccbdf6fbe3 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -775,16 +775,18 @@ inline std::vector fspx_payload_from_parts(std::span code) { - if (code.size() < 36 || code.size() % 4) return false; - for (const std::size_t word : {0u, 3u, 6u}) { + if (code.size() < 24 || code.size() % 4) return false; + const auto word = [&](std::size_t i) { std::uint32_t v; - std::memcpy(&v, code.data() + 4 * word, 4); - if (v >> 16 != 0xD580) return false; - } - return true; + std::memcpy(&v, code.data() + 4 * i, sizeof(v)); + return v; + }; + if (word(0) >> 16 != 0xD580 || word(3) >> 16 != 0xD580) return false; + if (code.size() >= 36 && word(6) >> 16 == 0xD580) return true; + return (word(1) & 0xfffe0100u) == 0x03fe0100u && (word(4) & 0xfffe0100u) == 0x03fe0100u; } // What a compute shader's bytecode is looked up by in the translator's index. @@ -1026,11 +1028,14 @@ class ShaderLibrary { // Finds an FSPX program by its kind-6 SHA-256 across all stages so the stage comes from the index entry itself. const ShaderEntry* find_fspx_by_code(std::string_view fspx_code_sha256) const { + const ShaderEntry* match = nullptr; for (std::string_view st : {"vs", "ps", "ms", "gs", "cs"}) { const auto all = fspx_candidates(st, fspx_code_sha256); - if (!all.empty()) return all.front(); + if (all.empty()) continue; + if (match) return nullptr; // the code alone cannot distinguish two shader stages + match = all.front(); } - return nullptr; + return match; } // The entries for a program compute_program() found, by the key of its kind (docs/fspx.md, "Build and run-time diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 2d9bc5212e..b83bb83152 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -18,6 +18,8 @@ // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "vk_test_device.h" #include "d3d12_test_shaders.h" +#include "d3d12_native_graphics_fixture.h" +#include "test_temp_dir.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" #include "../shims/d3d12_xs_pso_stream.h" @@ -101,7 +103,8 @@ D3D12_MESH_SHADER_TIER mesh_tier(ID3D12Device* device) { int main(int argc, char** argv) { const bool pc_only = argc == 2 && std::string_view(argv[1]) == "--pc-stream-only"; - EXPECT(argc == 1 || pc_only); + const bool native_fspx = argc == 2 && std::string_view(argv[1]) == "--native-fspx"; + EXPECT(argc == 1 || pc_only || native_fspx); EXPECT(SetEnvironmentVariableW(L"LEONIDA_XS_STREAM_ENUM", pc_only ? L"0" : L"1")); vktest::Device d; d.request_mesh_shader = true; @@ -124,8 +127,14 @@ int main(int argc, char** argv) { ms_container[36 + 8 + 2] = 13; // DXIL mesh shader kind ms_old_container[36 + 8 + 2] = 13; const auto vs_container = shader_container(vs_program); - const auto library = std::filesystem::temp_directory_path() / "leonida_mesh_test"; - std::filesystem::create_directories(library); + testfiles::ScratchDir scratch("leonida_mesh_test"); + const auto& library = scratch.path(); + std::vector raw_ms, raw_ps; + if (native_fspx) { + raw_ms = native_code(ms_program, 3, false); + raw_ps = native_code(ps_program, 2, true); + EXPECT(write_native_code_index(library, "ms", LEONIDA_TEST_MS_SPV, raw_ms, LEONIDA_TEST_PS_SPV, raw_ps, false)); + } std::filesystem::copy_file(LEONIDA_TEST_MS_SPV, library / "ms_draw.spv", std::filesystem::copy_options::overwrite_existing); std::filesystem::copy_file(LEONIDA_TEST_MS_SPV, library / "ms_old.spv", std::filesystem::copy_options::overwrite_existing); std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); @@ -226,7 +235,6 @@ int main(int argc, char** argv) { EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } if (!d.mesh_shader) { - std::filesystem::remove_all(library); std::printf("no VK_EXT_mesh_shader on this device: only the refusal without it was checked\n"); return 77; } @@ -319,37 +327,43 @@ int main(int argc, char** argv) { bad.add(DepthStencil1Subobject{.inner = bounds}); EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p); - // A console stream: its numbering has no gap at 23, so its mesh shader is 24 (the PC's AS) and its - // RASTERIZER1 26 (the PC's DEPTH_STENCIL2). An AS without an MS is no PC stream, so the layer reads it with the - // console's numbering and makes the mesh PSO. The PC reading of the same bytes alone would refuse it. - D3D12_RASTERIZER_DESC1 raster1{}; - raster1.FillMode = D3D12_FILL_MODE_SOLID; - raster1.CullMode = D3D12_CULL_MODE_NONE; - raster1.DepthClipEnable = TRUE; - for (int with_raster1 = 0; with_raster1 < 2; ++with_raster1) { - Stream console; - console.add(RootSubobject{.inner = root.p}); - console.add(Subobject{.inner = ms}); - console.add(PsSubobject{.inner = ps}).add(TargetsSubobject{.inner = one_target()}); - if (with_raster1) - console.add(Subobject{.inner = raster1}); - console.add(MaskSubobject{.inner = UINT_MAX}); - Ref console_pso; - using Create = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); - const auto desc = console.desc(); - const HRESULT console_hr = reinterpret_cast(slot(device.p, 86))(device.p, &desc, IID_PPV_ARGS(&console_pso.p)); - if (pc_only) { - EXPECT(FAILED(console_hr) && !console_pso.p); - } else { - EXPECT(SUCCEEDED(console_hr) && console_pso.p); - // Slot 55 must also walk raw 26 as RASTERIZER1 and retain the mesh bytecode after the base is released. - using Derive = HRESULT(WINAPI*)(ID3D12Device*, ID3D12PipelineState*, UINT, const void*, REFIID, void**); - std::array record{}; - const std::uint32_t mask[] = {3, UINT_MAX}; - std::memcpy(record.data(), mask, sizeof(mask)); - mesh_pso.reset(); - EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 55))( - device.p, console_pso.p, 1, record.data(), IID_PPV_ARGS(&mesh_pso.p))) && mesh_pso.p); + if (native_fspx) { + mesh_pso.reset(); + EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, one_target().RTFormats[0], {}, + &mesh_pso.p, raw_ms, raw_ps)) && mesh_pso.p); + } else { + // A console stream: its numbering has no gap at 23, so its mesh shader is 24 (the PC's AS) and its + // RASTERIZER1 26 (the PC's DEPTH_STENCIL2). An AS without an MS is no PC stream, so the layer reads it with the + // console's numbering and makes the mesh PSO. The PC reading of the same bytes alone would refuse it. + D3D12_RASTERIZER_DESC1 raster1{}; + raster1.FillMode = D3D12_FILL_MODE_SOLID; + raster1.CullMode = D3D12_CULL_MODE_NONE; + raster1.DepthClipEnable = TRUE; + for (int with_raster1 = 0; with_raster1 < 2; ++with_raster1) { + Stream console; + console.add(RootSubobject{.inner = root.p}); + console.add(Subobject{.inner = ms}); + console.add(PsSubobject{.inner = ps}).add(TargetsSubobject{.inner = one_target()}); + if (with_raster1) + console.add(Subobject{.inner = raster1}); + console.add(MaskSubobject{.inner = UINT_MAX}); + Ref console_pso; + using Create = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + const auto desc = console.desc(); + const HRESULT console_hr = reinterpret_cast(slot(device.p, 86))(device.p, &desc, IID_PPV_ARGS(&console_pso.p)); + if (pc_only) { + EXPECT(FAILED(console_hr) && !console_pso.p); + } else { + EXPECT(SUCCEEDED(console_hr) && console_pso.p); + // Slot 55 must also walk raw 26 as RASTERIZER1 and retain the mesh bytecode after the base is released. + using Derive = HRESULT(WINAPI*)(ID3D12Device*, ID3D12PipelineState*, UINT, const void*, REFIID, void**); + std::array record{}; + const std::uint32_t mask[] = {3, UINT_MAX}; + std::memcpy(record.data(), mask, sizeof(mask)); + mesh_pso.reset(); + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 55))( + device.p, console_pso.p, 1, record.data(), IID_PPV_ARGS(&mesh_pso.p))) && mesh_pso.p); + } } } // Even a known mesh FSSM must not reinterpret type 24 if the container declares another stage. @@ -721,7 +735,6 @@ int main(int argc, char** argv) { fence.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } - std::filesystem::remove_all(library); unsigned mismatches = 0; for (UINT row = 0; row < size; ++row) { @@ -744,9 +757,10 @@ int main(int argc, char** argv) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("D3D-29: mesh tier 1; mesh and VS PSOs from pipeline state streams (9 refused as invalid, 2 as not " + std::printf("D3D-29: mesh tier 1; %s (9 refused as invalid, 2 as not " "implemented); DispatchMesh over X, Y and Z and a stream VS draw matched all %u pixels; wrong-kind " "draws fail at execution, oversized grids at Close; statistics queries around mesh draws resolve\n", + native_fspx ? "slot-57 mesh PSO and a stream VS PSO" : "mesh and VS PSOs from pipeline state streams", size * size); return 0; } diff --git a/runtime/test/d3d12_native_graphics_fixture.h b/runtime/test/d3d12_native_graphics_fixture.h index 4eaac5bd73..f8d5f2fd1c 100644 --- a/runtime/test/d3d12_native_graphics_fixture.h +++ b/runtime/test/d3d12_native_graphics_fixture.h @@ -9,6 +9,34 @@ namespace d3d12test { namespace np = leonida::native_pso; inline constexpr np::Digest producer_digest{1}, ps_digest{2}, stale_digest{3}; +// Synthetic kind-6 hash carriers. Preserve the M1.5 pixel shader's data table at byte 0x100. +inline std::vector native_code(std::vector payload, std::uint32_t marker, bool short_header) { + const std::uint32_t words[] = {0xd5800000, 0x03fe0100, marker, 0xd5800000, 0x03fe0100, 0, + short_header ? 0xbf810000u : 0xd5800000u, 0x03fe0100, 0, 0xbf810000}; + if (payload.size() < sizeof(words)) payload.resize(sizeof(words)); + std::memcpy(payload.data(), words, sizeof(words)); + return payload; +} + +inline bool write_native_code_index(const std::filesystem::path& library, const char* producer_stage, + const std::filesystem::path& producer_module, const std::vector& producer, + const std::filesystem::path& pixel_module, const std::vector& pixel, + bool pixel_reads_code) { + const auto gfx = library / "fspx_gfx"; + std::filesystem::create_directories(gfx); + std::filesystem::copy_file(producer_module, gfx / "producer.spv", std::filesystem::copy_options::overwrite_existing); + std::filesystem::copy_file(pixel_module, gfx / "pixel.spv", std::filesystem::copy_options::overwrite_existing); + std::ofstream index(gfx / "index.json", std::ios::binary); + index << R"({"producer":{"stage":")" << producer_stage << R"(","fspx_code_sha256":")" << leonida::sha256_hex(producer) + << R"(","push_constant_bytes":144,"outputs":[0])"; + if (std::string_view(producer_stage) == "ms") + index << R"(,"root_window":{"sgpr":16,"dword":8},"local_size":[32,1,1],"max_vertices":4,"max_primitives":2)"; + index << R"(},"pixel":{"stage":"ps","fspx_code_sha256":")" << leonida::sha256_hex(pixel) + << R"(","push_constant_bytes":144,"inputs":[0],"outputs":[0],"uses_code_base":)" + << (pixel_reads_code ? "true" : "false") << "}}\n"; + return index.good(); +} + inline bool write_native_catalog(const std::filesystem::path& dest, const char* producer_stage, const std::vector& producer, const std::vector& ps) { std::error_code ec; @@ -29,7 +57,8 @@ inline bool write_native_catalog(const std::filesystem::path& dest, const char* } inline HRESULT create_native_pso(ID3D12Device* device, ID3D12RootSignature* root, DXGI_FORMAT target, - const np::Digest& producer, ID3D12PipelineState** out) { + const np::Digest& producer, ID3D12PipelineState** out, + std::span producer_code = {}, std::span pixel_code = {}) { std::array state{}; state[0x10] = static_cast(target); std::memset(state.data() + 0x1c, 0xff, sizeof(UINT)); @@ -45,8 +74,10 @@ inline HRESULT create_native_pso(ID3D12Device* device, ID3D12RootSignature* root np::GraphicsDesc desc{}; desc.root_signature = root; desc.state_b = {state.data(), state.size()}; - desc.stages[5].records = {v.data(), v.size()}; - desc.stages[2].records = {p.data(), p.size()}; + if (producer_code.empty() || producer != np::Digest{}) desc.stages[5].records = {v.data(), v.size()}; + if (!producer_code.empty()) desc.stages[5].code = {producer_code.data(), producer_code.size()}; + if (pixel_code.empty()) desc.stages[2].records = {p.data(), p.size()}; + else desc.stages[2].code = {pixel_code.data(), pixel_code.size()}; using Create = HRESULT(WINAPI*)(void*, const np::GraphicsDesc*, const IID*, void**); return reinterpret_cast(slot(device, 57))(device, &desc, &__uuidof(ID3D12PipelineState), reinterpret_cast(out)); diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index aa3f5ec280..1bc40c91dd 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -122,7 +122,8 @@ int main(int argc, char** argv) { int main(int argc, char** argv) { const bool derived_zero = argc == 2 && std::strcmp(argv[1], "--derived-zero") == 0; const bool derived_restore = argc == 2 && std::strcmp(argv[1], "--derived-restore") == 0; - const bool native = derived_zero || derived_restore || (argc == 2 && std::strcmp(argv[1], "--native-pso") == 0); + const bool raw_native = argc == 2 && std::strcmp(argv[1], "--native-fspx") == 0; + const bool native = derived_zero || derived_restore || raw_native || (argc == 2 && std::strcmp(argv[1], "--native-pso") == 0); EXPECT(argc == 1 || native); vktest::Device d; const auto device_status = d.initialize(); @@ -143,11 +144,18 @@ int main(int argc, char** argv) { EXPECT(library.find("vs", leonida::sha256_hex(vs_program)) && library.find("ps", leonida::sha256_hex(ps_program))); EXPECT(library.find("ps", leonida::sha256_hex(ps_program))->uses_code_base); std::optional scratch; + std::vector raw_vs, raw_ps; if (native) { scratch.emplace("leonida_native_graphics_draw"); std::error_code ec; std::filesystem::copy(root_dir / "spirv", scratch->path() / "spirv", std::filesystem::copy_options::recursive, ec); EXPECT(!ec && write_native_catalog(scratch->path(), "vs", vs_program, ps_program)); + if (raw_native) { + raw_vs = native_code(vs_program, 1, true); + raw_ps = native_code(ps_program, 2, false); + EXPECT(write_native_code_index(scratch->path() / "spirv", "vs", root_dir / "spirv/vs_m15.spv", raw_vs, + root_dir / "spirv/ps_m15.spv", raw_ps, true)); + } } #endif const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); @@ -237,9 +245,22 @@ int main(int argc, char** argv) { if (native) { EXPECT(FAILED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], stale_digest, &unknown.p)) && !unknown.p); EXPECT(FAILED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], np::Digest{}, &unknown.p)) && !unknown.p); - EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], producer_digest, &pso.p)) && pso.p); + if (raw_native) { + auto stale = raw_vs; + stale.back() ^= 1; + EXPECT(FAILED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], {}, &unknown.p, stale, raw_ps)) && !unknown.p); + Ref recovered; + EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], stale_digest, + &recovered.p, raw_vs, raw_ps)) && recovered.p); + } + const auto digest = raw_native ? np::Digest{} : producer_digest; + EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], digest, &pso.p, raw_vs, raw_ps)) && pso.p); Ref duplicate; - EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], producer_digest, &duplicate.p))); + EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], digest, &duplicate.p, raw_vs, raw_ps))); + if (raw_native) { + std::fill(raw_vs.begin(), raw_vs.end(), 0); + std::fill(raw_ps.begin(), raw_ps.end(), 0); // deferred binding must still see the original code table + } EXPECT(duplicate.p && duplicate.p != pso.p); EXPECT(rt::d3d12::graphics_pipeline_id(pso.p) != 0 && rt::d3d12::graphics_pipeline_id(duplicate.p) == rt::d3d12::graphics_pipeline_id(pso.p)); @@ -514,11 +535,12 @@ int main(int argc, char** argv) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("M1.5: translated VS+PS found by FSSM hash drew three draws; %u of %u pixels exact, %u edge " + std::printf("M1.5: translated VS+PS found by %s hash drew three draws; %u of %u pixels exact, %u edge " "pixels on the triangle's diagonal (%u its colour, %u the clear colour). User data from a descriptor " "table and root constants, V# vertex fetch from the arena, PS constants " "through the code base\n", - target_extent * target_extent - edge, target_extent * target_extent, edge, edge_triangle, edge_clear); + raw_native ? "kind-6" : "FSSM", target_extent * target_extent - edge, target_extent * target_extent, + edge, edge_triangle, edge_clear); #endif return 0; } diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 5fae4621c6..772e2e6a17 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -1348,6 +1348,12 @@ int main(int argc, char** argv) { "fspx_gfx PS entry preserves stage and its spv filename, under the folder prefix"); check(vs_entry && vs_entry->stage == "vs" && vs_entry->spv_file == "fspx_gfx/4444444444444444_libvs_00002.spv", "fspx_gfx VS entry preserves stage and its spv filename, under the folder prefix"); + const std::string shared_code(64, 'a'); + std::ofstream(tmp_dir / "fspx_gfx" / "index.json") + << R"({"a":{"stage":"ps","fspx_code_sha256":")" << shared_code + << R"("},"b":{"stage":"vs","fspx_code_sha256":")" << shared_code << "\"}}"; + check(lib.load_fspx_only(tmp_dir) && !lib.find_fspx_by_code(shared_code), + "a raw hash assigned to two graphics stages cannot identify the stage"); std::filesystem::remove_all(tmp_dir, ec); } } diff --git a/runtime/test/shader_library_corpus_test.cpp b/runtime/test/shader_library_corpus_test.cpp index 962cc7e4d5..35bd052b57 100644 --- a/runtime/test/shader_library_corpus_test.cpp +++ b/runtime/test/shader_library_corpus_test.cpp @@ -7,10 +7,8 @@ // from the DXIL/XDAT/XBCH entry, hash it and look it up under the container's stage. The stage comes from the DXIL // part's program header, not from index.json. Every container has to resolve to its own entry (the one named after // the file, or one of its `~N` duplicates) with a readable SPIR-V module, and every RPF index entry has to be reached -// by a container. The entries from /fspx/index.json, /bvh/index.json and /exe/index.json -// are counted apart: their programs come from the FidelityFX DLL, from XboxBvhBuilder.dll and from the game -// executable, not from the carved DXBC containers, so they are not orphans. Containers with more than one 0x0D -// payload are +// by a container. Auxiliary entries are counted separately, including the graphics programs of the pipeline library +// in fspx_gfx/index.json. Containers with more than one 0x0D payload are // counted, and their first payload must not stand in for the last: that is the rule fssm_program follows, so a // regression to the first payload fails here. // @@ -194,15 +192,16 @@ int main() { if (containers == 0) fail("no .dxbc containers in", dxbc_dir); const std::size_t rpf_entries = library.size() - library.fspx_size() - library.fspx_compute_size() - - library.bvh_size() - library.exe_size(); + library.fspx_gfx_size() - library.bvh_size() - library.exe_size(); if (reached.size() != rpf_entries) fail(std::to_string(reached.size() > rpf_entries ? reached.size() - rpf_entries : rpf_entries - reached.size()) + " RPF index entries not matched one to one", spirv_dir); - std::printf("%zu containers, %zu RPF index entries, %zu reached, %zu FSPX index entries, %zu BVH builder index " - "entries, %zu executable index entries; %zu containers with more than one program; " + std::printf("%zu containers, %zu RPF index entries, %zu reached, %zu FSPX index entries, " + "%zu graphics FSPX entries, %zu BVH builder index entries, %zu executable index entries; " + "%zu containers with more than one program; " "%zu not translated; %d failures\n", - containers, rpf_entries, reached.size(), library.fspx_size(), library.bvh_size(), + containers, rpf_entries, reached.size(), library.fspx_size(), library.fspx_gfx_size(), library.bvh_size(), library.exe_size(), multi, untranslated, failures); if (untranslated) std::fprintf(stderr, "%zu container(s) have no index entry: the translator left them out, so the lookup had " diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 2448ab7b82..564ce2fc5b 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -524,6 +524,12 @@ int fspx_checks() { no_prologue[14] ^= 0x01; // word 3: bits 31..16 no longer 0xD580 CHECK(compute_program(no_prologue).kind == Kind::none); CHECK(compute_program(std::vector(code.begin(), code.begin() + 35)).kind == Kind::none); + std::vector short_code; + for (const auto word : {0xd5800000u, 0x03fe0100u, 1u, 0xd5800000u, 0x03fe0100u, 2u, 0xbf810000u}) + put32(short_code, word); + CHECK(compute_program(short_code).kind == Kind::fspx); + short_code[17] = 0; // the second VOP3 no longer carries a literal + CHECK(compute_program(short_code).kind == Kind::none); CHECK(compute_program(bytes("not a shader")).kind == Kind::none); return 0; } diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index d1dd93461c..2ae7a9f721 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -2692,6 +2692,14 @@ int check_slot57_native_graphics() { EXPECT(g_factory_calls == asked + 1 && out == nullptr && mock->calls[10] == 2); } + // A two-program fallback would silently omit this occupied block. + const unsigned stage_word = 0; + desc.stages[6].code = {&stage_word, sizeof(stage_word)}; + g_factory_result = E_NOTIMPL; + EXPECT(hr_of(raw(device, 57, word(&desc), word(&pipeline_iid), word(&out))) == E_NOTIMPL); + EXPECT(out == nullptr && mock->calls[10] == 2); + desc.stages[6] = {}; + // A description the proxy cannot read is refused before the factory sees it, and does not fall back either. g_factory_result = S_OK; void* reserved = VirtualAlloc(nullptr, 0x10000, MEM_RESERVE, PAGE_NOACCESS); diff --git a/tests/test_library_shaders_stage.py b/tests/test_library_shaders_stage.py index 09253ffe0a..fce179153f 100644 --- a/tests/test_library_shaders_stage.py +++ b/tests/test_library_shaders_stage.py @@ -1,5 +1,4 @@ -"""make_game.py's pipeline-library step (library_shaders): the compute pipelines of the library in shaders.rpf, which -the executable creates with Xbox device slot 67 (docs/shader_library.md, docs/fspx.md). +"""make_game.py's pipeline-library step, for Xbox device slots 67 and 57 (docs/shader_library.md, docs/fspx.md). python -I tests/test_library_shaders_stage.py @@ -65,12 +64,17 @@ def fake_translate(self, disasm, spirv, jobs, emulate=False, fallbacks=()): with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(index, f) + def compute_group(self, signature="llvm-mc 23", jobs=4, emulate=False, fallbacks=()): + settings = (make_game.library_settings(self.archive, signature, emulate, fallbacks) + if os.path.isfile(self.archive) else None) + make_game.translate_library_stages(self.archive, self.work, "library", ("cs",), settings, jobs, emulate, fallbacks) + def run_step(self, signature="llvm-mc 23", jobs=4, emulate=False, fallbacks=(), py=None, translate=None): self.calls = [] with mock.patch.object(make_game, "py", py or self.fake_py), \ mock.patch.object(make_game, "translate", translate or self.fake_translate), \ mock.patch.object(make_game, "log", lambda *a: None): - make_game.library_shaders(self.game, self.work, signature, jobs, emulate=emulate, fallbacks=fallbacks) + self.compute_group(signature, jobs, emulate, fallbacks) return [tool for tool, _ in self.calls] def test_runs_once_then_nothing(self): @@ -93,6 +97,47 @@ def test_no_archive_skips_the_step(self): self.assertEqual(self.run_step(), []) self.assertFalse(os.path.exists(self.spirv)) + def test_graphics_only_archive_and_invalid_graphics_metadata(self): + programs = [prog(0x11111111), prog(0x22222222)] + self.write_archive(make_archive(build([(NONE, NONE, {0: (0, NONE), 1: (1, NONE)})], [], [], programs))) + fake_mc = os.path.join(self.tmp.name, "mc.py") + with open(fake_mc, "w", encoding="utf-8", newline="\n") as f: + f.write("print('\\ts_endpgm')\n") + gfx = os.path.join(self.work, "shaders", "spirv", "fspx_gfx") + + def translate(disasm, out, jobs, **flags): + self.assertEqual(out, gfx) + os.makedirs(out, exist_ok=True) + index = {} + for i, stage in enumerate(("ps", "vs")): + name = f"lib_{stage}_{i:05d}" + with open(os.path.join(os.path.dirname(disasm), "fspx", name + ".code"), "rb") as f: + self.assertEqual(f.read(), programs[i]) + index[name] = {"stage": stage, "fspx_code_sha256": hashlib.sha256(programs[i]).hexdigest()} + with open(os.path.join(out, name + ".spv"), "wb") as f: + f.write(b"synthetic module") + with open(os.path.join(out, "index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump(index, f) + + with mock.patch.dict(os.environ, {"LLVM_MC": f'"{sys.executable}" "{fake_mc}"'}), \ + mock.patch.object(make_game, "translate", side_effect=translate) as translated: + make_game.library_shaders(self.game, self.work, "fake-mc", 1) + with mock.patch.object(make_game, "py", side_effect=AssertionError("valid groups must be reused")): + make_game.library_shaders(self.game, self.work, "fake-mc", 1) + self.assertEqual(translated.call_count, 1) + with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f: + self.assertEqual(json.load(f), {}) + index_path = os.path.join(gfx, "index.json") + with open(index_path, encoding="utf-8") as f: + index = json.load(f) + for invalid in ({"stage": "cs", "fspx_code_sha256": "a" * 64}, {"stage": "vs"}): + with self.subTest(invalid=invalid): + index["lib_vs_00001"] = invalid + with open(index_path, "w", encoding="utf-8", newline="\n") as f: + json.dump(index, f) + self.assertIsNone(make_game.graphics_library_stamp(os.path.join(self.work, "shaders", "fspx_gfx"), + gfx, "{}")) + def test_archive_that_is_gone_takes_the_old_index_with_it(self): self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) index = os.path.join(self.spirv, "index.json") @@ -283,8 +328,7 @@ def fake_py(tool, *args): with mock.patch.object(make_game, "py", fake_py), \ mock.patch.object(make_game.subprocess, "Popen", side_effect=fake_popen), \ mock.patch.object(make_game, "log", lambda *a: None): - make_game.library_shaders(self.game, self.work, "llvm-mc 23", jobs=3, emulate=True, - fallbacks=("--bary-fallback",)) + self.compute_group(jobs=3, emulate=True, fallbacks=("--bary-fallback",)) self.assertEqual([cmd[cmd.index("--shard") + 1] for cmd in spawned], ["0/3", "1/3", "2/3"]) for cmd in spawned: self.assertIn("--no-asm", cmd) @@ -297,8 +341,7 @@ def fake_py(tool, *args): spawned.clear() merges.clear() self.write_archive(b"updated archive") - make_game.library_shaders(self.game, self.work, "llvm-mc 23", jobs=3, emulate=True, - fallbacks=("--bary-fallback",)) + self.compute_group(jobs=3, emulate=True, fallbacks=("--bary-fallback",)) self.assertEqual([cmd[cmd.index("--shard") + 1] for cmd in spawned], ["0/3", "1/3", "2/3"]) self.assertEqual(len(merges), 1) @@ -321,7 +364,7 @@ def wait(self, timeout=None): mock.patch.object(make_game, "log", lambda *a: None), \ mock.patch("sys.stderr", new_callable=io.StringIO) as err: with self.assertRaises(SystemExit): - make_game.library_shaders(self.game, self.work, "llvm-mc 23", jobs=2) + self.compute_group(jobs=2) self.assertIn("shard 1 exited with 2", err.getvalue()) self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) self.assertFalse(os.path.exists(os.path.join(self.spirv, "library_build.json"))) @@ -414,7 +457,13 @@ def fake_py(tool, *args): elif tool == "shader_disasm.py": write("s_endpgm\n", dxbc, "disasm", "shader.s") elif tool == "shader_library.py": - write("s_endpgm\n", work, "shaders", "library", "disasm", "lib_cs_00007.s") + out = args[args.index("--out") + 1] + stages = args[args.index("--stages") + 1].split(",") + self.assertIn(stages, [["cs"], ["ps", "vs", "ms"]]) + entries = [{"file": f"lib_{s}.dxbc", "stage": s} for s in stages] + write(json.dumps(entries), out, "index.json") + for s in stages: + write("s_endpgm\n", out, "disasm", f"lib_{s}.s") def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): ran.append("translate") @@ -424,6 +473,13 @@ def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): "fspx_state_sha256": "s" * 64}}), spirv, "index.json") write("spv", spirv, "lib_cs_00007.spv") + elif os.path.basename(spirv) == "fspx_gfx": + index = {} + for stage in ("ps", "vs", "ms"): + name = "lib_" + stage + index[name] = {"stage": stage, "fspx_code_sha256": hashlib.sha256(stage.encode()).hexdigest()} + write("module " + stage, spirv, name + ".spv") + write(json.dumps(index), spirv, "index.json") else: write('{"shader": {"stage": "cs"}}', spirv, "index.json") @@ -438,18 +494,40 @@ def stage(): make_game.shaders(game, work, 2) return list(ran) - self.assertEqual(stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate", - "shader_library.py", "translate"]) - self.assertEqual(translate_jobs, [(os.path.join(work, "shaders", "spirv"), 2), - (os.path.join(work, "shaders", "spirv", "library"), 2)]) + group = ["shader_library.py", "translate"] + spirv = os.path.join(work, "shaders", "spirv") + gfx = os.path.join(spirv, "fspx_gfx") + groups = [(os.path.join(spirv, "library"), 2), (gfx, 2)] + self.assertEqual(stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate"] + group * 2) + self.assertEqual(translate_jobs, [(spirv, 2)] + groups) + self.assertEqual(stage(), []) + # An older workspace only has the compute index. Backfill graphics without touching it or the corpus. + shutil.rmtree(gfx) + self.assertEqual(stage(), group) + self.assertEqual(translate_jobs, [(gfx, 2)]) + self.assertEqual(stage(), []) + os.unlink(os.path.join(gfx, "lib_ms.spv")) + self.assertEqual(stage(), group) + self.assertEqual(translate_jobs, [(gfx, 2)]) + # A truncated index still has valid keys and modules. Its build marker must reject it. + with open(os.path.join(gfx, "index.json"), encoding="utf-8") as f: + partial = json.load(f) + del partial["lib_ps"] + write(json.dumps(partial), gfx, "index.json") + self.assertEqual(stage(), group) + self.assertEqual(translate_jobs, [(gfx, 2)]) self.assertEqual(stage(), []) with open(archive_path, "wb") as f: f.write(b"archive v2") - self.assertEqual(stage(), ["shader_library.py", "translate"]) - self.assertEqual(translate_jobs, [(os.path.join(work, "shaders", "spirv", "library"), 2)]) + self.assertEqual(stage(), group * 2) + self.assertEqual(translate_jobs, groups) self.assertEqual(stage(), []) self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", "index.json"))) self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", "library", "index.json"))) + os.unlink(archive_path) + self.assertEqual(stage(), []) + self.assertFalse(os.path.exists(os.path.join(gfx, "index.json"))) + self.assertFalse(os.path.exists(os.path.join(gfx, "library_build.json"))) if __name__ == "__main__":