diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md index ed3a254d71..1d7153ebb6 100644 --- a/docs/embedded_shaders.md +++ b/docs/embedded_shaders.md @@ -393,3 +393,13 @@ reason to run again, a second run that leaves no duplicate containers, the repor 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` 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`, 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). +`ShaderLibrary::load` does not read `/exe` yet (a separate runtime change). `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 ff5ff76767..7df2892d14 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 @@ -1318,6 +1318,7 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate verify_translation_completeness(dxbc, spirv) fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks) bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) + exe_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) log("shaders: done") @@ -1536,6 +1537,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 and len(programs[1]) < len(programs[0]): + 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/tests/test_bvh_shaders_stage.py b/tests/test_bvh_shaders_stage.py index fd7e1a5ad7..6b5cc5fc6b 100644 --- a/tests/test_bvh_shaders_stage.py +++ b/tests/test_bvh_shaders_stage.py @@ -379,7 +379,7 @@ def fake_py(tool_name, *args): # the FSPX step keeps its output only when the index names a program whose module is there name = "SortKeys" if builder else "Upscale" write('{"%s": {"stage": "cs", "fssm_sha256": "%s"}}' % (name, "a" * 64) if builder else - '{"%s": {"stage": "cs"}}' % name, out, "index.json") + '{"%s": {"stage": "cs", "fspx_code_sha256": "%s"}}' % (name, "c" * 64), out, "index.json") write("", out, name + ".spv") def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): diff --git a/tests/test_exe_shaders_stage.py b/tests/test_exe_shaders_stage.py new file mode 100644 index 0000000000..a34c17a926 --- /dev/null +++ b/tests/test_exe_shaders_stage.py @@ -0,0 +1,385 @@ +"""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(), []) + + def test_empty_cached_index_is_rebuilt(self): + """A cached index.json with no usable entries ({} or all error entries) must not be reused as finished.""" + self.assertEqual(self.run_step(), TOOLS) + for bad_index in ("{}", '{"container_00": {"error": "ValueError: synthetic"}}'): + with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: + f.write(bad_index) + self.assertEqual(self.run_step(), TOOLS) + 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"]) + + +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: + 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()