"""Tests for tools/tex_export.py, on synthetic textures and swizzle equations (no game data, no addrlib header). python -m pytest tests/test_tex_export.py -q """ import pytest # noqa: E402 (keeps the CI bash loop from running this file) import json import os import struct import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) np = pytest.importorskip("numpy") import tex_export as T # noqa: E402 def linear_eq(bpe, xor=False): """A 4 KB equation in the shape eq4k returns: byte bits, then x bits, then y bits (row-major in the tile). With xor=True each x bit also takes a y bit, which keeps it a bijection but no longer row-major.""" lb = (4096 // bpe).bit_length() - 1 xb, yb = (lb + 1) // 2, lb - (lb + 1) // 2 low = bpe.bit_length() - 1 xs = [(1 << k, (1 << (k % yb)) if xor else 0) for k in range(xb)] return [(0, 0)] * low + xs + [(0, 1 << k) for k in range(yb)] @pytest.fixture def eq(monkeypatch): """Install synthetic equations in eq4k's cache, so nothing reads the addrlib header.""" def install(bpe, xor=False): monkeypatch.setitem(T._EQ, bpe, linear_eq(bpe, xor)) return install def tile(elements, offs, nbytes): """Inverse of detiling: put each row-major element at the address detile_offsets gives it.""" bpe = elements.shape[1] buf = np.zeros(nbytes, np.uint8) buf.reshape(-1, bpe)[offs] = elements return buf.tobytes() def gradient(we, he, bpe): y, x = np.mgrid[0:he, 0:we] e = np.zeros((he * we, bpe), np.uint8) e[:, 0] = (x * 255 // max(1, we - 1)).reshape(-1) e[:, 1] = (y * 255 // max(1, he - 1)).reshape(-1) e[:, 2] = 128 e[:, 3] = 255 return e def noise(nbytes, seed=1): return np.random.default_rng(seed).integers(0, 256, nbytes, dtype=np.uint8).tobytes() def write_blob(carve, archive, off, data): d = os.path.join(carve, archive) os.makedirs(d, exist_ok=True) with open(os.path.join(d, f"{off:012x}.bin"), "wb") as f: f.write(data) def texture(fmt, fmt_name, w, h, mips, data_off=0, gpu=0x1000, **extra): t = {"archive": "x.rpf", "cpu": 0xABC, "q_index": 3, "gpu": gpu, "gpu_size": 0, "fmt": fmt, "fmt_name": fmt_name, "w": w, "h": h, "mips": mips, "data_off": data_off} t.update(extra) return t # ---- eq4k ---- def test_import_does_not_read_the_addrlib_header(monkeypatch): import importlib.util import amd_swizzle def no_header(*a, **k): raise AssertionError("load() called at import") monkeypatch.setattr(amd_swizzle, "load", no_header) spec = importlib.util.spec_from_file_location("tex_export_fresh", T.__file__) spec.loader.exec_module(importlib.util.module_from_spec(spec)) def test_eq4k_reads_the_patterns_once_and_picks_the_entry_for_bpe(monkeypatch): calls = [] bits8 = [0, 0, 0] + [1 << k for k in range(5)] + [(1 << k) << 16 for k in range(4)] bits4 = [0, 0] + [1 << k for k in range(5)] + [(1 << k) << 16 for k in range(5)] nibbles = {"NIBBLE01": [bits8[:8], bits4[:8]], "NIBBLE2": [bits8[8:12], bits4[8:12]], "NIBBLE3": [[0] * 4], "NIBBLE4": [[0] * 4]} tables = {"GFX10_SW_4K_S_PATINFO": [(1, 1, 1, 0, 0, "SW_4K_S 4 bpe"), (1, 0, 0, 0, 0, "SW_4K_S 8 bpe")]} def fake_load(): calls.append(1) return nibbles, tables monkeypatch.setattr(T, "load", fake_load) monkeypatch.setattr(T, "_PATTERNS", []) monkeypatch.setattr(T, "_EQ", {}) assert T.eq4k(8) == linear_eq(8) assert T.eq4k(4) == linear_eq(4) assert T.eq4k(8) == linear_eq(8) assert len(calls) == 1 # ---- detile_offsets / level_bytes ---- @pytest.mark.parametrize("bpe", [1, 2, 4, 8, 16]) def test_linear_equation_detiles_row_major_tiles(eq, bpe): eq(bpe) offs, bw, bh = T.detile_offsets(bpe, 2 * 64, 2 * 64) assert bw * bh * bpe == 4096 we = 2 * 64 y, x = np.divmod(np.arange(we * we), we) tile_index = (y // bh) * (we // bw) + x // bw assert np.array_equal(offs, tile_index * (4096 // bpe) + (y % bh) * bw + x % bw) @pytest.mark.parametrize("bpe", [4, 8, 16]) def test_offsets_are_a_permutation_of_whole_tiles(eq, bpe): eq(bpe, xor=True) _, bw, bh = T.detile_offsets(bpe, 1, 1) we, he = 3 * bw, 2 * bh offs, _, _ = T.detile_offsets(bpe, we, he) assert sorted(offs.tolist()) == list(range(we * he)) assert T.level_bytes(we, he, bpe, bw, bh) == 6 * 4096 def test_partial_tiles_are_padded_to_whole_tiles(eq): eq(4) _, bw, bh = T.detile_offsets(4, 1, 1) assert T.level_bytes(1, 1, 4, bw, bh) == 4096 assert T.level_bytes(bw + 1, bh, 4, bw, bh) == 2 * 4096 offs, _, _ = T.detile_offsets(4, bw + 1, 1) assert int(offs.max()) == 4096 // 4 # first element of the second tile assert len(set(offs.tolist())) == bw + 1 # ---- dds_bytes ---- def test_dds_header_is_a_dx10_texture2d(): payload = bytes(range(64)) b = T.dds_bytes(16, 8, 71, payload) assert len(b) == 128 + 20 + len(payload) assert b[:4] == b"DDS " size, flags, h, w, linear = struct.unpack_from("I4s", b, pos) body = b[pos + 8:pos + 8 + n] if kind == b"IHDR": ihdr = struct.unpack(">IIBBBBB", body) elif kind == b"IDAT": idat += body pos += 12 + n w, h, depth, ctype, _, _, interlace = ihdr assert (depth, ctype, interlace) == (8, 6, 0) raw = zlib.decompress(idat) stride = 1 + w * 4 assert len(raw) == h * stride assert all(raw[y * stride] == 0 for y in range(h)) return w, h, b"".join(raw[y * stride + 1:(y + 1) * stride] for y in range(h)) def png_main(tmp_path, monkeypatch, capsys, textures, carve, *flags): index = tmp_path / "textures_index.json" index.write_text(json.dumps(textures), encoding="utf-8") out = tmp_path / "out" monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), carve, str(out), *flags]) code = T.main() return out, code, capsys.readouterr().out def tree(out): return sorted(os.path.relpath(os.path.join(r, f), out) for r, _, fs in os.walk(out) for f in fs) def test_main_accepts_png(tmp_path, monkeypatch): # the usage line documented --png, but argparse stopped with "unrecognized arguments" index = tmp_path / "textures_index.json" index.write_text("[]", encoding="utf-8") monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), str(tmp_path), str(tmp_path / "out"), "--png"]) assert T.main() is None def test_png_is_written_beside_the_dds_with_the_texels(eq, tmp_path, monkeypatch, capsys): carve, expected = build_case(eq, tmp_path, 28, top_first=True) t = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2) out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") assert code is None stem = f"{0xABC:012x}_3_64x64_R8G8B8A8_UNORM" assert tree(out) == ["export_log.json", f"x.rpf{os.sep}{stem}.dds", f"x.rpf{os.sep}{stem}.png"] w, h, rgba = read_png(out / "x.rpf" / (stem + ".png")) assert (w, h) == (64, 64) assert rgba == expected # RGBA8 texels pass through unchanged (the gradient sets alpha to 255) log = json.loads((out / "export_log.json").read_text(encoding="utf-8")) assert log[0]["export"]["png"] == "written" assert text.splitlines() == ["1 textures: {'ok:first': 1} -> " + str(out), "png: {'written': 1}"] def test_undecodable_format_keeps_the_dds_and_counts_unsupported(eq, tmp_path, monkeypatch, capsys): carve, expected = build_case(eq, tmp_path, 10, top_first=True) # R16G16B16A16_FLOAT: dds_png has no decoder t = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2) out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") assert code is None # main() returns None, so the process exits 0 assert tree(out) == ["export_log.json", f"x.rpf{os.sep}{0xABC:012x}_3_64x64_R16G16B16A16_FLOAT.dds"] assert (out / "x.rpf" / f"{0xABC:012x}_3_64x64_R16G16B16A16_FLOAT.dds").read_bytes()[148:] == expected assert json.loads((out / "export_log.json").read_text(encoding="utf-8"))[0]["export"]["png"] == "unsupported" assert text.splitlines()[1:] == ["png: {'unsupported': 1}"] def test_mixed_run_counts_each_kind(eq, tmp_path, monkeypatch, capsys): carve, _ = build_case(eq, tmp_path, 28, top_first=True) eq(8) with open(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin"), "rb") as f: write_blob(carve, "x.rpf", 0x2000, f.read() * 2) # enough bytes for the 8 bpe texture too textures = [texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2), texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2, gpu=0x2000), texture(9999, "X", 4, 4, 1, gpu=0x3000)] out, code, text = png_main(tmp_path, monkeypatch, capsys, textures, carve, "--png") assert text.splitlines()[1] == "png: {'written': 1, 'unsupported': 1}" assert len([f for f in tree(out) if f.endswith(".png")]) == 1 def test_png_module_is_not_imported_without_the_flag(eq, tmp_path, monkeypatch, capsys): monkeypatch.delitem(sys.modules, "dds_png", raising=False) carve, _ = build_case(eq, tmp_path, 28, top_first=True) png_main(tmp_path, monkeypatch, capsys, [texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2)], carve) assert "dds_png" not in sys.modules with open(T.__file__, encoding="utf-8") as f: assert not [line for line in f if line.startswith(("import dds_png", "from dds_png"))] def test_without_png_nothing_changes(eq, tmp_path, monkeypatch, capsys): carve, expected = build_case(eq, tmp_path, 28, top_first=True) t = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2) out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve) stem = f"{0xABC:012x}_3_64x64_R8G8B8A8_UNORM" assert tree(out) == ["export_log.json", f"x.rpf{os.sep}{stem}.dds"] assert text == f"1 textures: {{'ok:first': 1}} -> {out}\n" log = json.loads((out / "export_log.json").read_text(encoding="utf-8")) assert set(log[0]["export"]) == {"file", "place", "score", "heuristic"} def test_failed_png_write_keeps_the_texture_ok_and_is_counted(eq, tmp_path, monkeypatch, capsys): carve, _ = build_case(eq, tmp_path, 28, top_first=True) stem = f"{0xABC:012x}_3_64x64_R8G8B8A8_UNORM" blocked = tmp_path / "out" / "x.rpf" / (stem + ".png") blocked.mkdir(parents=True) # a directory at the PNG's path makes the write fail t = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2) out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") assert code is None assert (out / "x.rpf" / (stem + ".dds")).is_file() and blocked.is_dir() entry = json.loads((out / "export_log.json").read_text(encoding="utf-8"))[0]["export"] assert entry["png"].startswith("error:") lines = text.splitlines() assert lines[0].startswith("1 textures: {'ok:first': 1}") assert lines[1] == "png: {'" + entry["png"] + "': 1}" def test_stale_export_entry_is_not_counted(eq, tmp_path, monkeypatch, capsys): carve, _ = build_case(eq, tmp_path, 28, top_first=True) stale = {"file": "old.dds", "place": "first", "score": 1.0, "png": "written"} t = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2, gpu=0x5000, export=stale) # blob 0x5000 does not exist out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") assert text.splitlines()[0].startswith("1 textures: {'error:FileNotFoundError': 1}") assert text.splitlines()[1] == "png: {}" # ---- bad index / --out guards (#1607's class in main) ---- def _argv(monkeypatch, index, carve, out, *extra): monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), str(carve), str(out), *extra]) def test_main_reports_a_non_list_index_as_one_error_line(tmp_path, monkeypatch, capsys): index = tmp_path / "textures_index.json" index.write_text('{"files": []}', encoding="utf-8") out = tmp_path / "out" _argv(monkeypatch, index, tmp_path, out) assert T.main() == 2 err = capsys.readouterr().err assert err.startswith("ERROR: cannot read "), err assert len(err.strip().splitlines()) == 1, err assert not out.exists() def test_main_reports_an_index_row_without_keys(tmp_path, monkeypatch, capsys): index = tmp_path / "textures_index.json" index.write_text('[{"gpu": 0}]', encoding="utf-8") _argv(monkeypatch, index, tmp_path, tmp_path / "out") assert T.main() == 2 err = capsys.readouterr().err assert "ERROR: cannot read " in err, err assert "row has no 'archive'" in err, err assert "Traceback" not in err def test_main_rejects_an_out_that_is_a_file(tmp_path, monkeypatch, capsys): index = tmp_path / "textures_index.json" index.write_text("[]", encoding="utf-8") out = tmp_path / "existing.txt" out.write_text("x", encoding="utf-8") _argv(monkeypatch, index, tmp_path, out) assert T.main() == 2 err = capsys.readouterr().err assert "is a file, not a folder" in err, err assert out.read_text(encoding="utf-8") == "x" def test_main_reports_an_out_under_an_existing_file(tmp_path, monkeypatch, capsys): index = tmp_path / "textures_index.json" index.write_text("[]", encoding="utf-8") blocker = tmp_path / "file.txt" blocker.write_text("x", encoding="utf-8") _argv(monkeypatch, index, tmp_path, blocker / "sub") assert T.main() == 2 err = capsys.readouterr().err assert "ERROR: cannot create " in err, err assert "Traceback" not in err def test_main_reports_a_dangling_symlink_out(tmp_path, monkeypatch, capsys): index = tmp_path / "textures_index.json" index.write_text("[]", encoding="utf-8") link = tmp_path / "dangling-out" try: os.symlink(str(tmp_path / "missing-target"), str(link)) except (OSError, NotImplementedError): pytest.skip("symlinks are not available") _argv(monkeypatch, index, tmp_path, link) assert T.main() == 2 err = capsys.readouterr().err assert "ERROR: cannot create " in err, err assert "Traceback" not in err def test_main_still_accepts_an_empty_list(tmp_path, monkeypatch, capsys): index = tmp_path / "textures_index.json" index.write_text("[]", encoding="utf-8") out = tmp_path / "out" _argv(monkeypatch, index, tmp_path, out) assert T.main() in (None, 0) # main() has no explicit return; sys.exit(None) is exit 0 assert (out / "export_log.json").is_file()