diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md
index ed3a254d71..a1277dfc71 100644
--- a/docs/embedded_shaders.md
+++ b/docs/embedded_shaders.md
@@ -291,12 +291,13 @@ The last line also gets `--wave64-emulate` and the fallback flags of the build,
`0x80004001`) after 28 creations.
**Run time.** `ShaderLibrary::load(dir)` (`runtime/src/shader_library.h`) reads `
/index.json`, then
-`/fspx/index.json` and `/bvh/index.json` when they are there. The builder's entries are named
-`bvh/`, the path of their module below ``, and go into the table of the game's shaders, so
-`create_compute` finds them through the lookup it already had (`compute_program()` gives an `FSSM` program, looked up
-by `(cs, fssm_sha256)`). A missing or unreadable `bvh/index.json` leaves the other indexes loaded, and the main
-index is still required. `bvh_size()` counts the entries, which `shader_library_corpus_test` leaves out of the
-entries a carved container must reach, like the FSPX ones.
+`/fspx/index.json`, `/bvh/index.json`, and `/exe/index.json` when they are there. The builder's
+entries are named `bvh/` and the executable's `exe/`, the path of their module below ``, and both
+go into the table of the game's shaders, so graphics and compute pipeline creation find them through the lookup they
+already had (`fssm_program()` / `compute_program()` gives an `FSSM` program, looked up by `(stage, fssm_sha256)`). A
+missing or unreadable subfolder `index.json` leaves the other indexes loaded, and the main index is still required.
+`bvh_size()` and `exe_size()` count those entries, which `shader_library_corpus_test` leaves out of the entries a
+carved container must reach, like the FSPX ones.
**Measured: `LEONIDA_BVH_DEVICE=vulkan bvh_builder_test`** (package 1.0.2.1, `LEONIDA_BVH_RECORD62=1`,
`LEONIDA_SHADERS` on a folder holding this step's output and an empty main index, since only this step was run).
@@ -390,6 +391,17 @@ constructor's pipelines are created, not that a build produces the right tree (s
`tests/test_bvh_shaders_stage.py` runs the step on a synthetic DLL (hand-built containers around a made-up `FSSM`
blob, no game data): the key the extracted layout gives the translator, the tools and arguments, reuse and each
reason to run again, a second run that leaves no duplicate containers, the report of an untranslated program on
-every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` index (found by the
-container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test`
+every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` and `exe/` indexes (found
+by the container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test`
creates a pipeline through slot 62 whose only translation is in `/bvh/index.json`.
+
+**Retail executable (`exe_shaders()`).** After `bvh_shaders()`, `make_game.py`'s `shaders` stage runs
+`exe_shaders()` on `/game_scarlett_master.exe` when present (skipping cleanly and dropping any stale
+`/shaders/spirv/exe/index.json` and `exe_build.json` when the package has no executable). It runs the same
+four tools into `/shaders/exe` and `/shaders/spirv/exe` (without `--max-shared-memory`, since the
+executable's containers are 1 VS + 9 PS graphics shaders), tracking inputs in `exe_build.json` and logging
+translated/missing counts on every run. Measured on 1.0.2.1: 10 of 10 programs translate and pass `spirv-val`
+natively and with `--wave64-emulate`, `ShaderLibrary::load` finds all 10 (`1 VS + 9 PS`) by `(stage, fssm_sha256)`,
+and `vk_pipeline_check` passes 10/10 modules and 10/10 pipelines (0 failed, 0 skipped) on an AMD Radeon RX 9070 XT
+(RADV GFX1201, Mesa 26.2.6) and an AMD Ryzen 7 9800X3D integrated GPU (RADV RAPHAEL_MENDOCINO, Mesa 26.2.6).
+`tests/test_exe_shaders_stage.py` covers the step on synthetic VS/PS `PSV0` containers without game data.
diff --git a/make_game.py b/make_game.py
index 83cc5fd367..2be264cbf0 100644
--- a/make_game.py
+++ b/make_game.py
@@ -21,7 +21,7 @@
Stages (each skips work that is already done, so a stopped build continues where it left off):
check always first: file names and sizes against game/.json (add --full-check for SHA-256, slow)
shaders carve shaders.rpf, unpack the native RDNA2 code, disassemble, translate to SPIR-V; then the same for the
- compute programs inside amd_fidelityfx_upscaler_xbox.dll and XboxBvhBuilder.dll
+ programs inside amd_fidelityfx_upscaler_xbox.dll, XboxBvhBuilder.dll and game_scarlett_master.exe
assets models (OBJ), texture dictionaries and texture pools (DDS), audio banks (AWC; --wav adds PCM WAV)
BCPack uses strict decoding by default. For local calibration use /bcpack-calibration.json.
runtime build the loader (needs the game's executable to run, not to build). On Linux it is cross-built with
@@ -1344,6 +1344,7 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks)
bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
library_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
+ exe_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks)
log("shaders: done")
@@ -1633,6 +1634,88 @@ def bvh_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate:
f.write(settings + "\n")
+EXE_FILE = "game_scarlett_master.exe"
+EXE_TOOLS = BVH_TOOLS # pe_shader_containers.py, fssm_unpack.py and shader_disasm.py
+
+
+def exe_settings(exe: str, mc_signature: str, emulate: bool, fallbacks: tuple[str, ...]) -> str:
+ """What the executable's embedded shader outputs depend on, as one line: the executable, the extracting,
+ unpacking and translating tools, llvm-mc, the wave64 mode and the fallback flags."""
+ return json.dumps({"exe": file_sha256(exe), "tools": sources_digest(TOOLS, EXE_TOOLS),
+ "translator": translation_sources_digest(), "llvm_mc": mc_signature,
+ "wave64_emulate": bool(emulate), "fallbacks": list(fallbacks)}, sort_keys=True)
+
+
+def exe_report(programs: "tuple[list[str], list[str]]") -> None:
+ """One line with the counts, and one that names every program left without a module. It is printed on every
+ run, also when the step itself is reused: a program the translator has no rule for is never dropped quietly."""
+ extracted, missing = programs
+ log(f"shaders: {len(extracted) - len(missing)} of {len(extracted)} {EXE_FILE} programs translated")
+ if missing:
+ log(f"shaders: NOT translated: {', '.join(missing)}. The runtime has no module for "
+ f"{'it' if len(missing) == 1 else 'them'}, so any pipeline using it will miss its shader. "
+ "When the step runs, rdna2spirv.py prints the instruction each one stops at "
+ "(docs/embedded_shaders.md, section 2)")
+
+
+def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: bool = False,
+ fallbacks: tuple[str, ...] = ()) -> None:
+ """game_scarlett_master.exe's embedded graphics shaders (docs/embedded_shaders.md, section 2):
+ pe_shader_containers.py extracts the executable's DXBC containers into /shaders/exe, fssm_unpack.py and
+ shader_disasm.py unpack and disassemble their FSSM programs there, as for a shader from shaders.rpf, and
+ rdna2spirv.py translates them into /shaders/spirv/exe, where the runtime's shader library finds them by
+ fssm_sha256. The game's RPF shaders neither feed nor depend on this step.
+
+ The 10 programs take seconds, so the step runs whole. Reuse requires both indexes, the translated modules and a
+ matching exe_build.json (exe_settings)."""
+ exe = os.path.join(game, EXE_FILE)
+ unpacked = os.path.join(work, "shaders", "exe")
+ spirv = os.path.join(work, "shaders", "spirv", "exe")
+ extracted = os.path.join(unpacked, "index.json")
+ unpack_index = os.path.join(unpacked, "fssm_index.json")
+ translated = os.path.join(spirv, "index.json")
+ settings_file = os.path.join(spirv, "exe_build.json")
+ if not os.path.isfile(exe):
+ # A work folder used before with a package that had the executable still holds that run's index, and the
+ # runtime loads /exe/index.json whenever it is there. Without the index the old modules are not found.
+ drop(translated, settings_file)
+ log(f"shaders: no {EXE_FILE} in the game folder, so no executable shader programs to translate")
+ return
+ settings = exe_settings(exe, mc_signature, emulate, fallbacks)
+ programs = bvh_programs(unpacked, spirv) if read_shader_setting(settings_file) == settings else None
+ if programs:
+ exe_report(programs)
+ return
+ log(f"shaders: extracting and translating the embedded shader programs of {EXE_FILE}")
+ drop(translated, settings_file, extracted, unpack_index)
+ # pe_shader_containers.py never overwrites a container (a second run would write _NN.dxbc beside the
+ # first), and a program that no longer translates must not keep a module from the run before.
+ for folder, suffixes in ((unpacked, (".dxbc",)), (os.path.join(unpacked, "fssm"), (".fssm",)),
+ (os.path.join(unpacked, "disasm"), (".s",)), (spirv, (".spv", ".spvasm"))):
+ if os.path.isdir(folder):
+ with os.scandir(folder) as entries:
+ for entry in entries:
+ if entry.name.endswith(suffixes) and entry.is_file(follow_symlinks=False):
+ os.unlink(entry.path)
+ py("pe_shader_containers.py", exe, "--extract", unpacked)
+ py("fssm_unpack.py", unpacked, "--carve-index", extracted)
+ # rdna2spirv.py reads each program's stage from index.json and its FSSM blob from fssm/, both in the parent of
+ # the listings' folder, so the disassembly sits inside the extraction folder as it does for shaders.rpf.
+ disasm = os.path.join(unpacked, "disasm")
+ py("shader_disasm.py", os.path.join(unpacked, "fssm"), "--unpack-index", unpack_index, "--out", disasm,
+ "--mcpu", "gfx1013", "--jobs", jobs)
+ extra = (["--wave64-emulate"] if emulate else []) + list(fallbacks)
+ py("rdna2spirv.py", disasm, "--out", spirv, "--no-asm", *extra)
+ programs = bvh_programs(unpacked, spirv)
+ if not programs or len(programs[1]) == len(programs[0]):
+ drop(translated) # an empty or unreadable index would read as a finished step
+ fail(f"shaders: none of the {EXE_FILE} programs translated, so their index is not kept. Run the shaders "
+ "stage again; if it happens again, the tool output above is why.")
+ exe_report(programs)
+ with open(settings_file, "w", encoding="utf-8", newline="\n") as f:
+ f.write(settings + "\n")
+
+
WAVE64_MODES = ("auto", "on", "off")
# The translator's fallback flags make_game.py can forward, and the argparse attribute each one reads.
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 9f752317ee..787ef843ed 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -843,16 +843,18 @@ struct ShaderEntry {
class ShaderLibrary {
public:
- // Reads /index.json, then the indexes of the programs make_game.py translates from the package's DLLs, each
- // when it is there:
+ // Reads /index.json, then the indexes of the programs make_game.py translates from the package's PE images,
+ // each when it is there:
// - /fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/" (docs/fspx.md);
// - /bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/" and found by
// fssm_sha256 like the game's own shaders (docs/embedded_shaders.md);
// - /library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable
// creates with slot 67; entries named "library/" and found by fspx_code_sha256 and fspx_state_sha256
- // like the FSPX ones (docs/shader_library.md).
- // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. Both folders
- // are optional: a missing or unreadable index there leaves the main one, and the other folder's, loaded.
+ // like the FSPX ones (docs/shader_library.md);
+ // - /exe/index.json, game_scarlett_master.exe's embedded FSSM programs, entries named "exe/" and
+ // found by fssm_sha256 like the game's own shaders (docs/embedded_shaders.md).
+ // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The folders
+ // are optional: a missing or unreadable index there leaves the main one, and the other folders', loaded.
bool load(const std::filesystem::path& dir, std::string* error = nullptr) {
const auto fail = [&](const std::string& why) {
if (error) *error = why;
@@ -870,7 +872,7 @@ class ShaderLibrary {
} catch (...) {
return fail("index.json could not be read");
}
- for (const char* sub_folder : {"fspx", "bvh", "library"}) {
+ for (const char* sub_folder : {"fspx", "bvh", "library", "exe"}) {
try {
const auto ignore = [](const std::string&) { return false; };
const std::filesystem::path sub = folder / sub_folder;
@@ -893,6 +895,9 @@ class ShaderLibrary {
// Entries loaded from /bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes
// their containers itself.
std::size_t bvh_size() const { return bvh_count_; }
+ // Entries loaded from /exe/index.json. No RPF container reaches these either: game_scarlett_master.exe
+ // embeds their containers itself.
+ std::size_t exe_size() const { return exe_count_; }
// The first entry for this program. Two containers can hold the same FSSM program with different input
// signatures; `candidates` returns all of them.
@@ -1000,6 +1005,7 @@ class ShaderLibrary {
count_ = 0;
fspx_count_ = 0;
bvh_count_ = 0;
+ exe_count_ = 0;
}
for (const auto& [name, meta] : root.object) {
const Json* hash = meta.find("fssm_sha256");
@@ -1065,6 +1071,7 @@ class ShaderLibrary {
if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_;
if (prefix == "bvh/") ++bvh_count_;
+ if (prefix == "exe/") ++exe_count_;
++count_;
}
return true;
@@ -1074,6 +1081,7 @@ class ShaderLibrary {
std::size_t count_ = 0;
std::size_t fspx_count_ = 0;
std::size_t bvh_count_ = 0;
+ std::size_t exe_count_ = 0;
// Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order.
Entries entries_;
Entries fspx_entries_;
diff --git a/runtime/test/shader_library_corpus_test.cpp b/runtime/test/shader_library_corpus_test.cpp
index 7fdba23743..bb0be8c72e 100644
--- a/runtime/test/shader_library_corpus_test.cpp
+++ b/runtime/test/shader_library_corpus_test.cpp
@@ -192,16 +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.bvh_size();
+ const std::size_t rpf_entries = library.size() - library.fspx_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 containers with more than one program; "
+ "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(), multi, untranslated,
- failures);
+ containers, rpf_entries, reached.size(), library.fspx_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 "
"nothing to find. Run the shaders stage again with a current translator.\n",
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index bf7ad80d10..467c4e6031 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -889,6 +889,66 @@ int main() {
std::filesystem::remove_all(dir);
}
+ // Executable embedded shaders (/exe/index.json): graphics (vs/ps) FSSM programs indexed alongside the game's
+ // own shaders, counted apart via exe_size(), and optional when missing or malformed.
+ {
+ const auto vs_container = container({{fixed, 25}});
+ const auto ps_container = container({{stored, 40}});
+ const std::string vs_hash = sha256_hex(fssm_program(vs_container));
+ const std::string ps_hash = sha256_hex(fssm_program(ps_container));
+ const auto code = fspx_code(0x5000);
+ const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0};
+ const auto write = [&](const std::filesystem::path& file, const std::string& text) {
+ std::ofstream out(file, std::ios::binary | std::ios::trunc);
+ out << text;
+ };
+ const std::string game = "\"cs_game\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + hash + "\"}";
+ const std::string vs_entry = "{\"stage\": \"vs\", \"fssm_sha256\": \"" + vs_hash +
+ "\", \"input_signature\": [{\"semantic\": \"POSITION\", \"semantic_index\": 0, "
+ "\"register\": 0, \"system_value\": 0, \"component_type\": \"float\"}]}";
+ const std::string ps_entry = "{\"stage\": \"ps\", \"fssm_sha256\": \"" + ps_hash + "\"}";
+ std::filesystem::create_directories(dir / "fspx");
+ std::filesystem::create_directories(dir / "bvh");
+ std::filesystem::create_directories(dir / "exe");
+ write(dir / "index.json", "{" + game + "}");
+ write(dir / "fspx" / "index.json",
+ "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" + sha256_hex(code) + "\"}}");
+ write(dir / "bvh" / "index.json",
+ "{\"BuilderProgram\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + hash + "\"}}");
+ write(dir / "exe" / "index.json",
+ "{\"container_00\": " + vs_entry + ",\n \"container_01\": " + ps_entry +
+ ",\n \"NoKey\": {\"error\": \"ValueError: synthetic\"}}");
+ {
+ std::ofstream spv(dir / "exe" / "container_00.spv", std::ios::binary);
+ spv.write(reinterpret_cast(words), sizeof(words));
+ std::ofstream spv_ps(dir / "exe" / "container_01.spv", std::ios::binary);
+ spv_ps.write(reinterpret_cast(words), sizeof(words));
+ }
+ ShaderLibrary exe;
+ CHECK(exe.load(dir.string(), &error) && exe.size() == 5 && exe.fspx_size() == 1 && exe.bvh_size() == 1 &&
+ exe.exe_size() == 2);
+ const ShaderEntry* vs = exe.find("vs", vs_hash);
+ const ShaderEntry* ps = exe.find("ps", ps_hash);
+ CHECK(vs && vs->name == "exe/container_00" && vs->input_signature.size() == 1 &&
+ vs->input_signature[0].semantic == "POSITION" && exe.spirv(*vs).size() == 5);
+ CHECK(ps && ps->name == "exe/container_01" && exe.spirv(*ps).size() == 5);
+ CHECK(exe.candidates("ps", vs_hash).empty() && exe.candidates("vs", ps_hash).empty() &&
+ exe.fspx_candidates("vs", vs_hash).empty());
+ // Same program in main index and exe/: main comes first (index order).
+ write(dir / "index.json", "{" + game + ",\n \"vs_same\": " + vs_entry + "}");
+ CHECK(exe.load(dir.string(), &error) && exe.size() == 6 && exe.exe_size() == 2);
+ const auto both = exe.candidates("vs", vs_hash);
+ CHECK(both.size() == 2 && both[0]->name == "vs_same" && both[1]->name == "exe/container_00");
+ write(dir / "index.json", "{" + game + "}");
+ // Broken or missing exe/index.json leaves main, fspx, and bvh loaded and resets exe_size() to 0.
+ write(dir / "exe" / "index.json", "{broken");
+ CHECK(exe.load(dir.string(), &error) && exe.size() == 3 && exe.exe_size() == 0 && exe.bvh_size() == 1 &&
+ exe.fspx_size() == 1 && !exe.find("vs", vs_hash));
+ std::filesystem::remove(dir / "exe" / "index.json");
+ CHECK(exe.load(dir.string(), &error) && exe.size() == 3 && exe.exe_size() == 0 && exe.find("cs", hash));
+ std::filesystem::remove_all(dir);
+ }
+
// The review case on #1911: one kind-6 program in two containers whose kind-0 entries differ (32x1x1 and
// 64x1x1), translated to two different modules. A container picks its own entry by fspx_state_sha256; a bare
// kind-6 program cannot tell them apart and is refused as ambiguous; with one module for the key it is accepted.
diff --git a/tests/test_exe_shaders_stage.py b/tests/test_exe_shaders_stage.py
new file mode 100644
index 0000000000..eae2e7f411
--- /dev/null
+++ b/tests/test_exe_shaders_stage.py
@@ -0,0 +1,376 @@
+"""make_game.py's executable shader step (exe_shaders) and the index key the runtime finds its programs by (fssm_sha256).
+
+ python -I tests/test_exe_shaders_stage.py
+
+Zero game data: the "executable" is synthetic bytes around hand-built DXBC containers whose PSV0 chunk names a
+graphics stage (VS/PS) and whose XBCH record is a zlib stream of a made-up FSSM blob; llvm-mc and the translator are
+stood in for the way tests/test_bvh_shaders_stage.py does. The extracting, unpacking and disassembling tools are the
+repository's own, run as make_game.py runs them.
+"""
+import hashlib
+import io
+import json
+import os
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+import zlib
+from unittest import mock
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+sys.path.insert(0, os.path.join(ROOT, "tools"))
+sys.path.insert(0, os.path.join(ROOT, "tests"))
+import make_game # noqa: E402
+import rdna2spirv # noqa: E402
+import shader_meta # noqa: E402
+from test_pe_shader_containers import container, xdat # noqa: E402
+
+TOOLS = ["pe_shader_containers.py", "fssm_unpack.py", "shader_disasm.py", "rdna2spirv.py"]
+ENDPGM = b"\x00\x00\x81\xbf"
+PSV0_STAGE_CODE = {"ps": 0, "vs": 1}
+
+
+def fssm_blob(seed: int) -> bytes:
+ """A made-up FSSM blob shader_disasm.py accepts: the code section offset at 0xC0, code 0x28 bytes into it, a
+ few filler words that differ per seed and the closing s_endpgm."""
+ head = bytearray(b"FSSM" + b"\x01\x01" + bytes(0xF0 - 6))
+ struct.pack_into(" bytes:
+ """A minimal PSV0 chunk whose ShaderStage byte at payload offset 4 + 24 names `stage`."""
+ payload = bytearray(struct.pack(" bytes:
+ """DXBC { SFI0, PSV0 = stage, DXIL = program header + XDAT { 0x12, 0x0D = XBCH + zlib(blob), 0x07 = bitcode } }:
+ the parts of game_scarlett_master.exe's embedded containers the tools read (no ILDN chunk; docs/embedded_shaders.md
+ section 2)."""
+ packed = zlib.compress(blob)
+ xbch = b"XBCH" + struct.pack(" bytes:
+ """Containers between unrelated bytes, as the executable holds them."""
+ return b"MZ" + b"\0" * 126 + b"".join(c + b"\xcc" * 12 for c in containers)
+
+
+def tool(name: str, *args: str) -> subprocess.CompletedProcess:
+ return subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", name), *args],
+ capture_output=True, text=True)
+
+
+class IndexKey(unittest.TestCase):
+ """Extracted PSV0 containers without ILDN unpack to FSSM and give rdna2spirv the stage (vs/ps) and fssm_sha256."""
+
+ def test_the_extracted_layout_gives_the_translator_the_key_and_graphics_stages(self):
+ programs = [("container_00", "vs", fssm_blob(1)), ("container_01", "ps", fssm_blob(2))]
+ with tempfile.TemporaryDirectory() as t:
+ exe = os.path.join(t, make_game.EXE_FILE)
+ with open(exe, "wb") as f:
+ f.write(exe_like(*(exe_container(stage, blob) for _, stage, blob in programs)))
+ out = os.path.join(t, "exe")
+ r = tool("pe_shader_containers.py", exe, "--extract", out)
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+ r = tool("fssm_unpack.py", out, "--carve-index", os.path.join(out, "index.json"))
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+ os.makedirs(os.path.join(out, "disasm"))
+ rdna2spirv._STAGES = None
+ self.addCleanup(setattr, rdna2spirv, "_STAGES", None)
+ for name, stage, blob in programs:
+ with open(os.path.join(out, "fssm", name + ".fssm"), "rb") as f:
+ self.assertEqual(f.read(), blob)
+ listing = os.path.join(out, "disasm", name + ".s")
+ meta = shader_meta.collect(listing, name, [[]], [[]])
+ self.assertEqual(meta.get("fssm_sha256"), hashlib.sha256(blob).hexdigest())
+ self.assertNotIn("fspx_code_sha256", meta)
+ self.assertEqual(rdna2spirv.stage_of(name, listing), stage)
+
+
+class ExeStage(unittest.TestCase):
+ """Which tools exe_shaders() runs and what it reports. Each stand-in writes what the real tool writes last."""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.work = os.path.join(self.tmp.name, "work")
+ self.game = os.path.join(self.tmp.name, "game")
+ os.makedirs(self.game)
+ self.exe = os.path.join(self.game, make_game.EXE_FILE)
+ self.programs = {
+ "container_00": ("vs", fssm_blob(1)),
+ "container_01": ("ps", fssm_blob(2)),
+ "container_02": ("ps", fssm_blob(3)),
+ }
+ self.untranslated = set()
+ self.write_exe()
+ self.unpacked = os.path.join(self.work, "shaders", "exe")
+ self.spirv = os.path.join(self.work, "shaders", "spirv", "exe")
+ self.calls, self.logs = [], []
+
+ def write_exe(self):
+ with open(self.exe, "wb") as f:
+ f.write(exe_like(*(exe_container(stage, blob) for stage, blob in self.programs.values())))
+
+ def fake_translate(self, *args):
+ out = args[args.index("--out") + 1]
+ os.makedirs(out, exist_ok=True)
+ index = {}
+ for listing in sorted(os.listdir(args[0])):
+ name = listing[:-2]
+ if not listing.endswith(".s") or name in self.untranslated:
+ continue
+ with open(os.path.join(os.path.dirname(args[0]), "fssm", name + ".fssm"), "rb") as f:
+ stage = self.programs[name][0]
+ index[name] = {"stage": stage, "fssm_sha256": hashlib.sha256(f.read()).hexdigest()}
+ with open(os.path.join(out, name + ".spv"), "wb") as f:
+ f.write(b"module of " + name.encode())
+ with open(os.path.join(out, "index.json"), "w", encoding="utf-8", newline="\n") as f:
+ json.dump(index, f)
+
+ def fake_py(self, tool_name, *args):
+ self.calls.append((tool_name, args))
+ if tool_name == "pe_shader_containers.py":
+ os.makedirs(self.unpacked, exist_ok=True)
+ for name in self.programs:
+ open(os.path.join(self.unpacked, name + ".dxbc"), "wb").close()
+ with open(os.path.join(self.unpacked, "index.json"), "w", encoding="utf-8", newline="\n") as f:
+ json.dump([{"name": n, "file": n + ".dxbc", "stage": st} for n, (st, _) in self.programs.items()], f)
+ elif tool_name == "fssm_unpack.py":
+ os.makedirs(os.path.join(self.unpacked, "fssm"), exist_ok=True)
+ for name, (_, blob) in self.programs.items():
+ with open(os.path.join(self.unpacked, "fssm", name + ".fssm"), "wb") as f:
+ f.write(blob)
+ with open(os.path.join(self.unpacked, "fssm_index.json"), "w", encoding="utf-8", newline="\n") as f:
+ json.dump([{"name": n} for n in self.programs], f)
+ elif tool_name == "shader_disasm.py":
+ os.makedirs(os.path.join(self.unpacked, "disasm"), exist_ok=True)
+ for name in self.programs:
+ with open(os.path.join(self.unpacked, "disasm", name + ".s"), "w", encoding="utf-8",
+ newline="\n") as f:
+ f.write("s_endpgm\n")
+ elif tool_name == "rdna2spirv.py":
+ self.fake_translate(*args)
+
+ def run_step(self, signature="llvm-mc 23", emulate=False, fallbacks=(), py=None):
+ self.calls, self.logs = [], []
+ with mock.patch.object(make_game, "py", py or self.fake_py), \
+ mock.patch.object(make_game, "log", self.logs.append):
+ make_game.exe_shaders(self.game, self.work, signature, 3, emulate=emulate, fallbacks=fallbacks)
+ return [name for name, _ in self.calls]
+
+ def test_runs_once_then_only_reports(self):
+ self.assertEqual(self.run_step(), TOOLS)
+ (_, extract), (_, unpack), (_, disasm), (_, translate) = self.calls
+ self.assertEqual(extract, (self.exe, "--extract", self.unpacked))
+ self.assertEqual(unpack, (self.unpacked, "--carve-index", os.path.join(self.unpacked, "index.json")))
+ self.assertEqual(disasm, (os.path.join(self.unpacked, "fssm"), "--unpack-index",
+ os.path.join(self.unpacked, "fssm_index.json"), "--out",
+ os.path.join(self.unpacked, "disasm"), "--mcpu", "gfx1013", "--jobs", 3))
+ # Graphics shaders: no --max-shared-memory compute LDS cap.
+ self.assertEqual(translate, (os.path.join(self.unpacked, "disasm"), "--out", self.spirv, "--no-asm"))
+ self.assertTrue(os.path.isfile(os.path.join(self.spirv, "exe_build.json")))
+ self.assertIn(f"shaders: 3 of 3 {make_game.EXE_FILE} programs translated", self.logs)
+ self.assertEqual(self.run_step(), [])
+ self.assertEqual(self.logs, [f"shaders: 3 of 3 {make_game.EXE_FILE} programs translated"])
+
+ def test_the_real_tools_fill_the_folder_and_a_second_run_leaves_no_duplicates(self):
+ mc = os.path.join(self.tmp.name, "fake_mc.py")
+ with open(mc, "w", encoding="utf-8", newline="\n") as f:
+ f.write("print('\\ts_endpgm')\n")
+
+ def run_tool(tool_name, *args):
+ self.calls.append((tool_name, args))
+ if tool_name == "rdna2spirv.py":
+ return self.fake_translate(*args)
+ make_game.run([sys.executable, "-I", os.path.join(make_game.TOOLS, tool_name), *args],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+
+ with mock.patch.dict(os.environ, {"LLVM_MC": f'"{sys.executable}" "{mc}"'}):
+ for signature in ("llvm-mc 23", "llvm-mc 24"):
+ self.assertEqual(self.run_step(signature=signature, py=run_tool), TOOLS)
+ names = sorted(self.programs)
+ self.assertEqual(sorted(f for f in os.listdir(self.unpacked) if f.endswith(".dxbc")),
+ [n + ".dxbc" for n in names])
+ self.assertEqual(sorted(os.listdir(os.path.join(self.unpacked, "fssm"))),
+ [n + ".fssm" for n in names])
+ self.assertEqual(sorted(os.listdir(os.path.join(self.unpacked, "disasm"))),
+ [n + ".s" for n in names])
+ with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f:
+ index = json.load(f)
+ self.assertEqual({n: (index[n]["stage"], index[n]["fssm_sha256"]) for n in index},
+ {n: (st, hashlib.sha256(blob).hexdigest()) for n, (st, blob) in self.programs.items()})
+ self.assertIn(f"shaders: 3 of 3 {make_game.EXE_FILE} programs translated", self.logs)
+ self.assertEqual(self.run_step(signature="llvm-mc 24", py=run_tool), [])
+
+ def test_no_exe_no_step(self):
+ os.remove(self.exe)
+ self.assertEqual(self.run_step(), [])
+ self.assertFalse(os.path.exists(self.spirv))
+ self.assertFalse(os.path.exists(self.unpacked))
+
+ def test_an_exe_that_is_gone_takes_the_old_index_with_it(self):
+ self.assertEqual(self.run_step(), TOOLS)
+ index, settings = os.path.join(self.spirv, "index.json"), os.path.join(self.spirv, "exe_build.json")
+ self.assertTrue(os.path.isfile(index) and os.path.isfile(settings))
+ os.remove(self.exe)
+ self.assertEqual(self.run_step(), [])
+ self.assertFalse(os.path.exists(index))
+ self.assertFalse(os.path.exists(settings))
+ self.assertEqual(self.logs, [f"shaders: no {make_game.EXE_FILE} in the game folder, so no executable "
+ "shader programs to translate"])
+ self.assertEqual(self.run_step(), [])
+ self.write_exe()
+ self.assertEqual(self.run_step(), TOOLS)
+ self.assertTrue(os.path.isfile(index) and os.path.isfile(settings))
+
+ def test_each_input_change_runs_it_again(self):
+ self.run_step()
+ self.assertEqual(self.run_step(signature="llvm-mc 24"), TOOLS)
+ self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True), TOOLS)
+ self.assertIn("--wave64-emulate", self.calls[3][1])
+ flags = ("--no-float-controls",)
+ self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS)
+ self.assertIn("--no-float-controls", self.calls[3][1])
+ self.programs["container_02"] = ("ps", fssm_blob(4))
+ self.write_exe()
+ self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS)
+ self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), [])
+ with mock.patch.object(make_game, "translation_sources_digest", return_value="another translator"):
+ self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS)
+
+ def test_an_untranslated_program_is_named_on_every_run_and_the_step_still_finishes(self):
+ self.untranslated = {"container_01"}
+ for expected in (TOOLS, [], []):
+ self.assertEqual(self.run_step(), expected)
+ self.assertIn(f"shaders: 2 of 3 {make_game.EXE_FILE} programs translated", self.logs)
+ named = [line for line in self.logs if "NOT translated: container_01." in line]
+ self.assertEqual(len(named), 1, self.logs)
+ self.assertNotIn("container_00", named[0])
+ with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f:
+ self.assertEqual(sorted(json.load(f)), ["container_00", "container_02"])
+ self.assertFalse(os.path.exists(os.path.join(self.spirv, "container_01.spv")))
+
+ def test_nothing_translated_fails_and_keeps_no_index(self):
+ self.untranslated = set(self.programs)
+ with self.assertRaises(SystemExit), mock.patch("sys.stderr", new_callable=io.StringIO) as err:
+ self.run_step()
+ self.assertIn(f"none of the {make_game.EXE_FILE} programs translated", err.getvalue())
+ self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json")))
+ self.assertFalse(os.path.exists(os.path.join(self.spirv, "exe_build.json")))
+ self.untranslated = set()
+ self.assertEqual(self.run_step(), TOOLS)
+
+ def test_missing_cached_module_or_index_is_rebuilt(self):
+ self.assertEqual(self.run_step(), TOOLS)
+ module = os.path.join(self.spirv, "container_00.spv")
+ os.remove(module)
+ self.assertEqual(self.run_step(), TOOLS)
+ with open(module, "rb") as f:
+ self.assertEqual(f.read(), b"module of container_00")
+ self.assertEqual(self.run_step(), [])
+ os.remove(os.path.join(self.unpacked, "index.json"))
+ self.assertEqual(self.run_step(), TOOLS)
+ self.assertEqual(self.run_step(), [])
+
+
+class ShadersStageWithTheExe(unittest.TestCase):
+ """The whole shaders() stage with both DLLs and the executable: exe_shaders() runs last and runs alone when only
+ the executable changes."""
+
+ def test_exe_runs_after_bvh_and_alone_when_only_the_exe_changes(self):
+ from test_bvh_shaders_stage import builder_container, dll_like as bvh_dll
+ from test_fspx_shaders_stage import container as fspx_container, dll_like as fspx_dll, program
+ with tempfile.TemporaryDirectory() as t:
+ work, game = os.path.join(t, "work"), os.path.join(t, "game")
+ os.makedirs(game)
+ with open(os.path.join(game, make_game.FSPX_DLL), "wb") as f:
+ f.write(fspx_dll(fspx_container(program())))
+ with open(os.path.join(game, make_game.BVH_DLL), "wb") as f:
+ f.write(bvh_dll(builder_container("SortKeys", fssm_blob(1))))
+ exe = os.path.join(game, make_game.EXE_FILE)
+ with open(exe, "wb") as f:
+ f.write(exe_like(exe_container("vs", fssm_blob(2))))
+ ran = []
+ dxbc = os.path.join(work, "shaders", "dxbc")
+ bvh = os.path.join(work, "shaders", "bvh")
+ exe_dir = os.path.join(work, "shaders", "exe")
+
+ def write(text, *parts):
+ os.makedirs(os.path.dirname(os.path.join(*parts)), exist_ok=True)
+ with open(os.path.join(*parts), "w", encoding="utf-8", newline="\n") as f:
+ f.write(text)
+
+ def fake_py(tool_name, *args):
+ ran.append(tool_name)
+ if tool_name == "shader_carve.py":
+ write('[{"file": "shader.dxbc"}]', dxbc, "index.json")
+ elif tool_name == "pe_shader_containers.py":
+ if args[2] == exe_dir:
+ write('[{"name": "container_00", "file": "container_00.dxbc", "stage": "vs"}]',
+ exe_dir, "index.json")
+ else:
+ write('[{"name": "SortKeys", "file": "SortKeys.dxbc", "stage": "cs"}]', bvh, "index.json")
+ elif tool_name == "fssm_unpack.py":
+ if args[0] == exe_dir:
+ write('[{"name": "container_00"}]', exe_dir, "fssm_index.json")
+ elif args[0] == bvh:
+ write('[{"name": "SortKeys"}]', bvh, "fssm_index.json")
+ else:
+ write('[{"name": "shader"}]', dxbc, "fssm_index.json")
+ elif tool_name == "shader_disasm.py":
+ if args[0].startswith(exe_dir):
+ write("s_endpgm\n", exe_dir, "disasm", "container_00.s")
+ elif args[0].startswith(bvh):
+ write("s_endpgm\n", bvh, "disasm", "SortKeys.s")
+ else:
+ write("s_endpgm\n", dxbc, "disasm", "shader.s")
+ elif tool_name == "rdna2spirv.py":
+ out = args[args.index("--out") + 1]
+ if args[0].startswith(exe_dir):
+ write('{"container_00": {"stage": "vs", "fssm_sha256": "%s"}}' % ("b" * 64), out, "index.json")
+ write("", out, "container_00.spv")
+ elif args[0].startswith(bvh):
+ write('{"SortKeys": {"stage": "cs", "fssm_sha256": "%s"}}' % ("a" * 64), out, "index.json")
+ write("", out, "SortKeys.spv")
+ else:
+ # the FSPX step keeps its output only when the index names a program whose module is there,
+ # keyed by fspx_code_sha256 (make_game.fspx_cache_complete)
+ write('{"Upscale": {"stage": "cs", "fspx_code_sha256": "%s"}}' % ("c" * 64), out, "index.json")
+ write("", out, "Upscale.spv")
+
+ def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()):
+ ran.append("translate")
+ write("", spirv, "index.json")
+
+ def stage():
+ ran.clear()
+ with mock.patch.object(make_game, "py", fake_py), \
+ mock.patch.object(make_game, "need", lambda *a: None), \
+ mock.patch.object(make_game, "translate", fake_translate), \
+ mock.patch.object(make_game, "llvm_mc_signature", return_value="llvm-mc 23"), \
+ mock.patch.object(make_game, "log", lambda *a: None):
+ make_game.shaders(game, work, 2)
+ return list(ran)
+
+ self.assertEqual(stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate",
+ "fspx_unpack.py", "rdna2spirv.py", *TOOLS, *TOOLS])
+ self.assertEqual(stage(), [])
+ with open(exe, "wb") as f:
+ f.write(exe_like(exe_container("vs", fssm_blob(3))))
+ self.assertEqual(stage(), TOOLS)
+ for sub in ((), ("fspx",), ("bvh",), ("exe",)):
+ self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", *sub, "index.json")))
+
+
+if __name__ == "__main__":
+ unittest.main()