"""Search for the in-tile swizzle of a GPU texture by brute force. Within a tile of 2^B blocks, each address bit maps to one x or one y bit. Every ordering with the right x/y split is tried (bit k goes to the next free x or y bit), tiles are laid out row-major, and the ordering whose block-endpoint image is smoothest wins. Usage: python -I swizzle_search.py --bpe 8 --tile 65536 [--widths 1024,2048] [--tiles 48] [--out preview.png] """ import argparse import itertools import os import sys try: import numpy as np except ImportError: # main() checks the arguments first, then says numpy is missing in one line np = None sys.path.insert(0, os.path.dirname(__file__)) from tile_probe import block_feature, score, same_report_path # noqa: E402 def positions(seq, nblocks, tw, th, wblocks): idx = np.arange(nblocks, dtype=np.int64) per = tw * th tile, inner = idx // per, idx % per x = np.zeros_like(idx) y = np.zeros_like(idx) xi = yi = 0 for k, c in enumerate(seq): bit = (inner >> k) & 1 if c == "x": x |= bit << xi xi += 1 else: y |= bit << yi yi += 1 tiles_x = wblocks // tw return ((tile // tiles_x) * th + y) * wblocks + (tile % tiles_x) * tw + x def search(data, bpe, tile_bytes, widths, ntiles): raw = np.frombuffer(data[: len(data) // bpe * bpe], np.uint8).reshape(-1, bpe) feat = block_feature(raw, bpe) bits = int(np.log2(tile_bytes // bpe)) results = [] for xbits in sorted({bits // 2, (bits + 1) // 2}): tw, th = 1 << xbits, 1 << (bits - xbits) for wpx in widths: wb = wpx // 4 if wb % tw: continue tiles_x = wb // tw blocks_per_row = tiles_x * tw * th rows = min(max(1, ntiles // tiles_x), len(raw) // blocks_per_row) if not rows: continue n = blocks_per_row * rows for xs in itertools.combinations(range(bits), xbits): seq = ["x" if k in xs else "y" for k in range(bits)] pos = positions(seq, n, tw, th, wb) img = np.zeros((n, 3), np.float32) img[pos] = feat[:n] results.append((score(img.reshape(-1, wb, 3)), wpx, "".join(seq))) results.sort() return results def render(data, bpe, tile_bytes, wpx, seq, out): import io import struct from PIL import Image raw = np.frombuffer(data[: len(data) // bpe * bpe], np.uint8).reshape(-1, bpe) bits = len(seq) xbits = seq.count("x") tw, th = 1 << xbits, 1 << (bits - xbits) wb = wpx // 4 hb = min(len(raw) // wb // th * th, wb // th * th or th) n = wb * hb pos = positions(list(seq), n, tw, th, wb) lin = np.zeros((n, bpe), np.uint8) lin[pos] = raw[:n] hdr = bytearray(128) hdr[0:4] = b"DDS " struct.pack_into("high) {seq}") if a.out is not None: parent = os.path.dirname(os.path.abspath(a.out)) try: if parent: os.makedirs(parent, exist_ok=True) render(data, a.bpe, a.tile, res[0][1], res[0][2], a.out) except (OSError, ValueError) as e: detail = getattr(e, "strerror", None) or str(e) print(f"ERROR: cannot write {a.out}: {detail}", file=sys.stderr) return 2 print("preview ->", a.out) if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())