diff --git a/make_game.py b/make_game.py index 0f5c499cbc..42fd9ca4a2 100644 --- a/make_game.py +++ b/make_game.py @@ -1233,7 +1233,7 @@ def translated_index_is_empty(index: str) -> bool: def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulated: bool = False, - fallbacks: tuple[str, ...] = ()) -> None: + fallbacks: tuple[str, ...] = (), shader_list: str | None = None) -> None: src = os.path.join(game, "shaders.rpf") sh = os.path.join(work, "shaders") dxbc = os.path.join(sh, "dxbc") @@ -1249,11 +1249,14 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate signature = llvm_mc_signature() if not os.path.isfile(carved): log("shaders: carving shaders.rpf") - drop(translated, shard_plan, disassembled, disassembly_started, unpacked) + # A subset translation writes to its own directory and never touches the full index, so don't drop it. + if shader_list is None: + drop(translated, shard_plan, disassembled, disassembly_started, unpacked) py("shader_carve.py", src, dxbc) if unpacked_shader_stems(dxbc) is None: log("shaders: unpacking native code") - drop(translated, shard_plan, disassembled, disassembly_started) + if shader_list is None: + drop(translated, shard_plan, disassembled, disassembly_started) py("fssm_unpack.py", dxbc, "--carve-index", carved) # rdna2spirv.py finds index.json, the .dxbc files and fssm/ in the parent of the .s files' folder, so the # disassembly must sit inside the carve folder: next to it, every stage reads as "?" and is rejected. @@ -1263,7 +1266,8 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate if os.path.isfile(disassembled) or os.path.isfile(translated): log("shaders: llvm-mc changed or the saved disassembly could not be verified") log("shaders: resuming disassembly (gfx1013)" if resume else "shaders: disassembling (gfx1013)") - drop(translated, shard_plan) + if shader_list is None: + drop(translated, shard_plan) if not resume: drop(disassembly_started, disassembled) prepare_shader_disassembly(work, disasm, resume) @@ -1286,61 +1290,73 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate f.write("\n") os.replace(marker, disassembled) drop(disassembly_started) - # The translation also depends on the translator's own files, so their digest is kept beside it. A folder without - # it (from before the file existed), with an unreadable one or with another one is translated again; carving, unpacking and - # disassembly stay current. - sources_file = os.path.join(spirv, "translation_sources.sha256") - sources = translation_sources_digest() - if os.path.isfile(translated) and read_shader_setting(sources_file) != sources: - log("shaders: no matching translator fingerprint for the existing shaders: translating again") - drop(translated) - # The translation depends on --wave64-emulate, so the mode it was made with is kept beside it. A folder from - # before the file existed was translated without emulation. - mode_file = os.path.join(spirv, "wave64_emulate.txt") - had = read_shader_setting(mode_file, default="off") - want = requested_shader_mode(had, emulate, keep_emulated) - if want == "on" and not emulate: - # auto answers differently from run to run (a GPU asleep or hidden, vulkaninfo missing); emulated shaders are - # exact on every GPU, so they are kept rather than translating the whole corpus again. When they are - # translated again for another reason, or a stopped translation is retried, they stay emulated. - log("shaders: the shaders were translated with wave64 emulation and it stays on (exact on every GPU); " - "--wave64-emulate off translates them natively") - emulate = True - elif had != want and os.path.isfile(translated): - log(f"shaders: wave64 emulation is now {want} (the shaders were translated with it {had}): " - "translating again") - drop(translated) - # The translation also depends on the fallback flags (--no-float-controls, --bary-fallback, - # --texel-offset-fallback, --mesh-compute), so they are kept beside it like the wave64 mode. A folder from - # before the file existed was translated without them. - flags_file = os.path.join(spirv, "translator_flags.txt") - want_flags = translator_flags_setting(fallbacks) - had_flags = read_shader_setting(flags_file) - if had_flags != want_flags and os.path.isfile(translated): - log(f"shaders: the fallback flags are now {want_flags or 'none'} (the shaders were translated with " - f"{had_flags or 'none'}): translating again") - drop(translated) - if os.path.isfile(translated) and translated_index_is_empty(translated): - # An empty merge, or an index that cannot be read, is not a finished translation. The shard plan goes with it: - # its parts are what the empty merge read, so a retry has to translate them again rather than reuse them. - log("shaders: the saved translated index names no shaders: translating again") - drop(translated, shard_plan) - if not os.path.isfile(translated): - need("spirv-as", "Install the Vulkan SDK (it includes spirv-as and spirv-val) and reopen the terminal.") - need("spirv-val", "Install the Vulkan SDK and reopen the terminal.") - log(f"shaders: translating RDNA2 to SPIR-V on {jobs} processes (the longest step)") - # The mode and the translator's digest go down before the translation starts, while there is no index.json: - # a stop at any point then leaves either no index (translated again) or an index with the right mode and - # digest, never a guessed one. rdna2spirv.py --merge writes index.json last, after the stubs. - os.makedirs(spirv, exist_ok=True) - with open(mode_file, "w", encoding="utf-8", newline="\n") as f: - f.write(want + "\n") - with open(flags_file, "w", encoding="utf-8", newline="\n") as f: - f.write(want_flags + "\n") - with open(sources_file, "w", encoding="utf-8", newline="\n") as f: - f.write(sources + "\n") - translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks) - verify_translation_completeness(dxbc, spirv) + if shader_list is not None: + # Subset translation: write to a separate directory, never touch the full index. None of the full-index + # fingerprint checks (translator digest, wave64 mode, fallback flags) apply: we never read or overwrite + # spirv/index.json, and we never call verify_translation_completeness(). + subset_spirv = os.path.join(spirv, "subset") + os.makedirs(subset_spirv, exist_ok=True) + log(f"shaders: translating listed shaders to {subset_spirv}") + translate(disasm, subset_spirv, jobs, emulate=emulate, fallbacks=fallbacks, + shader_list=shader_list) + else: + # Full translation with fingerprint checks: the translator's own files, wave64 mode and fallback flags + # all gate reuse of the saved index. + sources_file = os.path.join(spirv, "translation_sources.sha256") + sources = translation_sources_digest() + if os.path.isfile(translated) and read_shader_setting(sources_file) != sources: + log("shaders: no matching translator fingerprint for the existing shaders: translating again") + drop(translated) + # The translation depends on --wave64-emulate, so the mode it was made with is kept beside it. A folder from + # before the file existed was translated without emulation. + mode_file = os.path.join(spirv, "wave64_emulate.txt") + had = read_shader_setting(mode_file, default="off") + want = requested_shader_mode(had, emulate, keep_emulated) + if want == "on" and not emulate: + # auto answers differently from run to run (a GPU asleep or hidden, vulkaninfo missing); emulated + # shaders are exact on every GPU, so they are kept rather than translating the whole corpus again. + # When they are translated again for another reason, or a stopped translation is retried, they stay + # emulated. + log("shaders: the shaders were translated with wave64 emulation and it stays on (exact on every GPU); " + "--wave64-emulate off translates them natively") + emulate = True + elif had != want and os.path.isfile(translated): + log(f"shaders: wave64 emulation is now {want} (the shaders were translated with it {had}): " + "translating again") + drop(translated) + # The translation also depends on the fallback flags (--no-float-controls, --bary-fallback, + # --texel-offset-fallback, --mesh-compute), so they are kept beside it like the wave64 mode. A folder from + # before the file existed was translated without them. + flags_file = os.path.join(spirv, "translator_flags.txt") + want_flags = translator_flags_setting(fallbacks) + had_flags = read_shader_setting(flags_file) + if had_flags != want_flags and os.path.isfile(translated): + log(f"shaders: the fallback flags are now {want_flags or 'none'} (the shaders were translated with " + f"{had_flags or 'none'}): translating again") + drop(translated) + if os.path.isfile(translated) and translated_index_is_empty(translated): + # An empty merge, or an index that cannot be read, is not a finished translation. The shard plan goes + # with it: its parts are what the empty merge read, so a retry has to translate them again rather than + # reuse them. + log("shaders: the saved translated index names no shaders: translating again") + drop(translated, shard_plan) + if not os.path.isfile(translated): + need("spirv-as", "Install the Vulkan SDK (it includes spirv-as and spirv-val) and reopen the terminal.") + need("spirv-val", "Install the Vulkan SDK and reopen the terminal.") + log(f"shaders: translating RDNA2 to SPIR-V on {jobs} processes (the longest step)") + # The mode and the translator's digest go down before the translation starts, while there is no + # index.json: a stop at any point then leaves either no index (translated again) or an index with the + # right mode and digest, never a guessed one. rdna2spirv.py --merge writes index.json last, after the + # stubs. + os.makedirs(spirv, exist_ok=True) + with open(mode_file, "w", encoding="utf-8", newline="\n") as f: + f.write(want + "\n") + with open(flags_file, "w", encoding="utf-8", newline="\n") as f: + f.write(want_flags + "\n") + with open(sources_file, "w", encoding="utf-8", newline="\n") as f: + f.write(sources + "\n") + translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks) + verify_translation_completeness(dxbc, spirv) native_pso_hashes(dxbc, spirv) fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks) bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) @@ -1926,17 +1942,22 @@ def _stop_procs(procs: list) -> None: def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False, - fallbacks: tuple[str, ...] = ()) -> None: + fallbacks: tuple[str, ...] = (), shader_list: str | None = None) -> None: """rdna2spirv.py runs on one core: start one --shard per job side by side, then merge their index parts. A shard publishes shard.json and then index.part.json. Both are needed to reuse it. A run stopped part-way, or during the merge, keeps those parts when it resumes with the same --jobs, wave64 mode, fallback - flags and translator source, and starts only the shards that have none. shaders() drops the plan whenever an - earlier step reruns.""" + flags, translator source and shader list, and starts only the shards that have none. shaders() drops the plan + whenever an earlier step reruns.""" os.makedirs(spirv, exist_ok=True) plan_path = os.path.join(spirv, SHARD_PLAN) plan = {"jobs": jobs, "wave64_emulate": bool(emulate), "fallbacks": list(fallbacks), "translator": translator_digest()} + if shader_list is not None: + # The list content is part of the plan identity: overwriting the same list file with a different + # selection must not reuse shards translated for the old list. + with open(shader_list, "rb") as f: + plan["shader_list"] = hashlib.sha256(f.read()).hexdigest() try: with open(plan_path, encoding="utf-8") as f: same = json.load(f) == plan @@ -1960,6 +1981,8 @@ def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False, tool = os.path.join(TOOLS, "rdna2spirv.py") extra = ["--wave64-emulate"] if emulate else [] extra.extend(fallbacks) + if shader_list is not None: + extra.extend(["--shader-list", shader_list]) if todo: which = f"0..{jobs - 1}" if len(todo) == jobs else ",".join(str(i) for i in todo) log(f" rdna2spirv.py {disasm} --out {spirv} --shard {which}/{jobs}" + "".join(" " + e for e in extra)) @@ -2758,7 +2781,7 @@ def _invoke_stage(name: str, fn) -> None: def run_build_stages(stages: list, *, game: str, work: str, out: str, v: dict, wav: bool, jobs: int, runtime_build: str | None, emulate: bool, keep_emulated: bool, - fallbacks: tuple[str, ...], overlap: bool = True) -> None: + fallbacks: tuple[str, ...] = (), shader_list: str | None = None, overlap: bool = True) -> None: """Run build stages after check. With overlap=True (default), shaders/assets/runtime share the machine and pipelines starts once shaders (and a selected runtime rebuild) are ready. With overlap=False, stages run in order.""" cpu_heavy = [s for s in ("shaders", "assets") if s in stages] @@ -2768,7 +2791,8 @@ def run_build_stages(stages: list, *, game: str, work: str, out: str, v: dict, w progress = StageBoard([s for s in ("shaders", "assets", "runtime", "pipelines") if s in stages]) def fn_shaders(): - shaders(game, work, shader_jobs, emulate=emulate, keep_emulated=keep_emulated, fallbacks=fallbacks) + shaders(game, work, shader_jobs, emulate=emulate, keep_emulated=keep_emulated, + fallbacks=fallbacks, shader_list=shader_list) def fn_assets(): assets(game, work, wav, jobs, dump_jobs=dump_jobs) @@ -2908,6 +2932,9 @@ def main() -> int: help="keep s0..s31 in 128 push-constant bytes and move heap/code base to a set-1 uniform " "block; on by itself when the runtime's GPU reports maxPushConstantsSize below what " "the shaders need (144, or 152 with --mesh-compute)") + ap.add_argument("--shader-list", metavar="FILE", type=nonempty_path, + help="translate only shaders whose stem is listed in FILE (one stem per line); " + "skips the completeness check, for testing on a subset instead of all 26,503") ap.add_argument("--no-tui", action="store_true", help="plain console logs (default when stdout is not a TTY); skip the LEONIDA setup screen " "and per-stage log view") @@ -3040,12 +3067,12 @@ def main() -> int: tui_board.set_summary(f"build 0% ยท {', '.join(build_stages)}") run_build_stages(stages, game=game, work=work, out=out, v=v, wav=a.wav, jobs=a.jobs, runtime_build=runtime_build, emulate=emulate, keep_emulated=keep_emulated, - fallbacks=fallbacks, overlap=overlap) + fallbacks=fallbacks, shader_list=a.shader_list, overlap=overlap) tui_board.set_summary(f"finished in {(time.time() - t0) / 60:.0f} min") else: run_build_stages(stages, game=game, work=work, out=out, v=v, wav=a.wav, jobs=a.jobs, runtime_build=runtime_build, emulate=emulate, keep_emulated=keep_emulated, - fallbacks=fallbacks, overlap=overlap) + fallbacks=fallbacks, shader_list=a.shader_list, overlap=overlap) log(f"finished in {(time.time() - t0) / 60:.0f} min") return 0 diff --git a/tests/test_make_game_empty_translation.py b/tests/test_make_game_empty_translation.py index 0d310226bb..15ce89dcea 100644 --- a/tests/test_make_game_empty_translation.py +++ b/tests/test_make_game_empty_translation.py @@ -171,6 +171,64 @@ def test_a_stale_index_after_a_failed_shard_that_cannot_be_removed(self): self.assertIn("rdna2spirv.py: shard 0 exited with 1.", self.failure('{"old": {}}', shard_code=1)) +class ShadersStageSubsetTest(unittest.TestCase): + """shaders() with --shader-list: writes to a separate subset directory, never touches the full index.""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.work = tmp.name + self.dxbc = os.path.join(self.work, "shaders", "dxbc") + self.spirv = os.path.join(self.work, "shaders", "spirv") + os.makedirs(self.dxbc) + os.makedirs(self.spirv) + # Pre-populate a full index that must survive the subset run. + write(self.index(), json.dumps({"shader_full": {"stage": "ps", "fssm_sha256": "deadbeef"}})) + + def index(self): + return os.path.join(self.spirv, "index.json") + + def run_stage(self, shader_list=None): + calls = [] + + def fake_py(tool, *args): + if tool == "shader_carve.py": + write(os.path.join(self.dxbc, "index.json"), json.dumps([{"file": "shader.dxbc"}])) + elif tool == "fssm_unpack.py": + write(os.path.join(self.dxbc, "fssm_index.json"), json.dumps([{"name": "shader"}])) + elif tool == "shader_disasm.py": + write(os.path.join(self.dxbc, "disasm", "shader.s"), "synthetic listing\n") + + def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=(), shader_list=None): + calls.append((spirv, shader_list)) + os.makedirs(spirv, exist_ok=True) + write(os.path.join(spirv, "index.json"), json.dumps({"shader_subset": {"stage": "ps"}})) + + 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="test llvm-mc 21"), \ + mock.patch.object(make_game, "log", lambda *a: None): + make_game.shaders(os.path.join(self.work, "game"), self.work, 2, shader_list=shader_list) + return calls + + def test_subset_translates_to_subset_dir_and_full_index_survives(self): + calls = self.run_stage(shader_list=["shader_subset"]) + # translate() was called once, with the subset directory and the shader list + self.assertEqual(len(calls), 1) + spirv_dir, sl = calls[0] + self.assertEqual(spirv_dir, os.path.join(self.spirv, "subset")) + self.assertEqual(sl, ["shader_subset"]) + # The full index is untouched. + with open(self.index(), encoding="utf-8") as f: + self.assertEqual(json.load(f), {"shader_full": {"stage": "ps", "fssm_sha256": "deadbeef"}}) + # The subset index exists with just the subset entry. + subset_index = os.path.join(self.spirv, "subset", "index.json") + self.assertTrue(os.path.exists(subset_index)) + with open(subset_index, encoding="utf-8") as f: + self.assertEqual(json.load(f), {"shader_subset": {"stage": "ps"}}) + + class RequireTranslatedShadersTest(unittest.TestCase): def setUp(self): tmp = tempfile.TemporaryDirectory() diff --git a/tests/test_rdna2spirv_cli.py b/tests/test_rdna2spirv_cli.py index 6ce0777e63..c991c53c86 100644 --- a/tests/test_rdna2spirv_cli.py +++ b/tests/test_rdna2spirv_cli.py @@ -164,6 +164,36 @@ def test_a_new_output_folder_with_missing_parents_still_works(self): self.assertIn("1 pass spirv-val", stdout) self.assertTrue((out / "ps_ok.spv").is_file()) + def test_shader_list_filters_translated_shaders(self): + # Only stems listed in --shader-list are translated; others in the folder are skipped. + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "disasm") + os.mkdir(src) + with open(os.path.join(src, "ps_keep.s"), "w", encoding="utf-8") as f: + f.write("\ts_endpgm\n") + with open(os.path.join(src, "ps_skip.s"), "w", encoding="utf-8") as f: + f.write("\ts_endpgm\n") + with open(os.path.join(tmp, "ps_keep.dxbc"), "wb") as f: + f.write(b"DXBC" + bytes(28)) + with open(os.path.join(tmp, "ps_skip.dxbc"), "wb") as f: + f.write(b"DXBC" + bytes(28)) + list_file = os.path.join(tmp, "list.txt") + with open(list_file, "w", encoding="utf-8", newline="\n") as f: + f.write("ps_keep\n") + out = os.path.join(tmp, "spirv") + p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", out, + "--shader-list", list_file, + "--no-asm", "--no-validate", "--assembler", "python"], + capture_output=True, text=True, errors="replace") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("1 translated", p.stdout) + self.assertTrue(os.path.exists(os.path.join(out, "ps_keep.spv"))) + self.assertFalse(os.path.exists(os.path.join(out, "ps_skip.spv"))) + # The index names only the listed shader. + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + index = json.load(f) + self.assertEqual(set(index), {"ps_keep"}) + def test_non_s_file_as_src_is_refused_with_usage_error(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "notes.txt") diff --git a/tests/test_shader_stage_resume.py b/tests/test_shader_stage_resume.py index e3645dbc5b..aec1319d1e 100644 --- a/tests/test_shader_stage_resume.py +++ b/tests/test_shader_stage_resume.py @@ -531,6 +531,69 @@ def test_a_kill_right_after_a_merge_for_new_sources_keeps_the_translation(self): self.assertEqual(self.run_stage(), []) # hours of translation are not redone +class SubsetListIdentityTest(unittest.TestCase): + """The shard plan's identity must include the shader list content, so changing the list + (even overwriting the same file) re-translates instead of reusing stale shards.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.spirv = os.path.join(self.tmp.name, "spirv") + os.makedirs(self.spirv) + self.list_path = os.path.join(self.tmp.name, "shaders.txt") + self.write_list("s0\ns1\n") + self.popen_calls = [] + self.popen_patch = mock.patch.object(make_game.subprocess, "Popen", self.fake_popen) + self.popen_patch.start() + self.addCleanup(self.popen_patch.stop) + self.py_patch = mock.patch.object(make_game, "py", lambda *a, **k: None) + self.py_patch.start() + self.addCleanup(self.py_patch.stop) + + def write_list(self, content): + with open(self.list_path, "w", encoding="utf-8", newline="\n") as f: + f.write(content) + + def fake_popen(self, cmd, **kw): + self.popen_calls.append(list(cmd)) + proc = mock.Mock() + proc.wait.return_value = 0 + proc.poll.return_value = 0 + return proc + + def finish_shards(self, jobs=2): + """Simulate finished shards from a previous translation.""" + for i in range(jobs): + with open(os.path.join(self.spirv, f"index.part{i}.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump({}, f) + with open(os.path.join(self.spirv, f"shard{i}.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump({}, f) + + def test_same_list_reuses_finished_shards(self): + make_game.translate("disasm", self.spirv, 2, shader_list=self.list_path) + self.popen_calls.clear() + self.finish_shards() + make_game.translate("disasm", self.spirv, 2, shader_list=self.list_path) + self.assertEqual(self.popen_calls, [], "same list and finished shards: nothing to translate") + + def test_changed_list_retranslates(self): + make_game.translate("disasm", self.spirv, 2, shader_list=self.list_path) + self.popen_calls.clear() + self.finish_shards() + self.write_list("s2\ns3\n") + make_game.translate("disasm", self.spirv, 2, shader_list=self.list_path) + self.assertNotEqual(self.popen_calls, [], "changed list: plan mismatch, re-translate") + + def test_overwriting_same_file_retranslates(self): + make_game.translate("disasm", self.spirv, 2, shader_list=self.list_path) + self.popen_calls.clear() + self.finish_shards() + # Overwrite the same file with different content + self.write_list("s2\ns3\n") + make_game.translate("disasm", self.spirv, 2, shader_list=self.list_path) + self.assertNotEqual(self.popen_calls, [], "same path, new content: plan mismatch, re-translate") + + class TranslationSourcesTest(unittest.TestCase): def test_the_list_covers_the_translator_and_native_catalog_imports(self): seen, todo = set(), ["rdna2spirv", "native_pso_hashes"] diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 920e858ae8..ac67b22936 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -18928,6 +18928,9 @@ def main(): ap.add_argument("--shard", type=_shard_arg, help="i/n: translate every n-th shader starting at i (run n processes in parallel, " "then merge the index.part*.json files with --merge)") + ap.add_argument("--shader-list", default=None, + help="only translate shaders whose stem is in this file (one stem per line); " + "used to translate a subset of the corpus without rebuilding all 26,503") ap.add_argument("--no-asm", action="store_true", help="delete each .spvasm once its .spv is written (the text is ~2.7x the binary: 35 GB for the corpus)") ap.add_argument("--assembler", choices=("spirv-as", "python"), default="spirv-as", @@ -19083,6 +19086,14 @@ def main(): files = files[:a.limit] if shard is not None: files = files[shard::sn] + if a.shader_list is not None: + wanted = set() + with open(a.shader_list, encoding="utf-8") as f: + for line in f: + name = line.strip() + if name: + wanted.add(name) + files = [p for p in files if os.path.splitext(os.path.basename(p))[0] in wanted] why, ok, valid = Counter(), 0, 0 meta = {} invalid = set()