Initial public release

This commit is contained in:
jhaizhou
2026-10-12 16:51:08 +08:00
commit 46578a2b5d
997 changed files with 218713 additions and 0 deletions
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
import datetime
import os
import re
import sys
ACCESS = re.compile(r"(?:fp|vp)_c1\)\._m0\[([^\]]+)\]")
DEFINITION = re.compile(r"\b(?:u?int|long|short)\s+(_\d+)\s*=\s*([^;]+);")
VARIABLE = re.compile(r"\b(_\d+)\b")
def bounded(index, definitions):
names = VARIABLE.findall(index)
current = names[-1] if names else index.strip()
for _ in range(8):
expression = definitions.get(current)
if expression is None:
return False
if re.search(r"\bmin\s*\(|\bclamp\s*\(|&\s*(?:0x[0-9a-fA-F]+|\d+)", expression):
return True
names = VARIABLE.findall(expression)
if not names:
return False
current = names[-1]
return False
def main():
if len(sys.argv) != 3:
raise SystemExit(f"用法:{sys.argv[0]} <dmsh_b 版本目录> <输出 tsv>")
version_dir, output = map(os.path.abspath, sys.argv[1:])
keys = []
for name in sorted(os.listdir(version_dir)):
if not name.endswith(".metal"):
continue
path = os.path.join(version_dir, name)
with open(path, encoding="utf-8") as stream:
source = stream.read()
accesses = ACCESS.findall(source)
if not accesses:
continue
definitions = dict(DEFINITION.findall(source))
if any(not index.strip().isdigit() and not bounded(index, definitions) for index in accesses):
keys.append(name[:-len("_b.metal")] if name.endswith("_b.metal") else name[:-6])
os.makedirs(os.path.dirname(output), exist_ok=True)
with open(output, "w", encoding="utf-8", newline="") as stream:
stamp = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
stream.write(f"# chain {os.path.basename(version_dir)} {stamp}\n")
for key in keys:
stream.write(key + "\n")
print(f"未证有界:{len(keys)} 个着色器")
if __name__ == "__main__":
main()
+483
View File
@@ -0,0 +1,483 @@
#!/usr/bin/env python3
# B 路线离线出包:Switch 原版着色器 → SPIR-V(dmsh_xlate,Ryujinx 翻译器)→ spirv-cross MSL → metallib + 回放反射 JSON。
# 运行时不翻译(iOS 无 JIT):产物进着色器缓存目录,文件名 = Switch 控制段键(dm_ctl_sha16,与 shader_map.tsv 第 4 列同)+「_b」。
# 查询作答来源:仓内的作答表 nvn/shader_facts.tsv(dmsh_facts.py)——贴图类型、顶点属性 / 片元输出分量类型、计算线程组大小与共享内存;出包不需要 PC 版文件。
# 用法:dmsh_build.py <Switch 包目录> <输出缓存目录> [键…](不给键 = 全部);产物实际写进 <输出缓存目录>/b-<链版本>/(IOSOUT 同),链版本见 dmsh_chain.py 环境:XLATE=翻译工具路径,DMSH_CAS=内容寻址缓存目录(缺省为输出缓存目录/cas),J=并发
# 程序本体内嵌的图形着色器(映射表 main.rodata@偏移 行)从 MAIN(Switch main NSO,缺省 3.3.94012 Update/ExeFS/main)解出;解 NSO 要 lz4,用 dm 的 venv python 跑
# 产物:<键>_b.metallib、<键>_b.json(回放反射,含驱动段 c0 / c2 的运行时读取偏移 drv_reads)、<键>_b.metal(MSL)
# 环境 IOSOUT=目录:同一份 MSL 经 dm/ios/tools/ios_metal.compile 同时出 iphoneos metallib + 反射(chain_metal 记 iOS 编译口径)
# 末尾汇总:成功 / 失败数与原因分布;驱动段读取的偏移分布(落在回放层能填的范围外的单列)
# Route B offline build: original Switch shaders → SPIR-V (dmsh_xlate, the Ryujinx translator) → spirv-cross MSL → metallib + replay reflection JSON.
# No translation at runtime (iOS has no JIT): build output goes into the shader cache directory, file name = Switch control segment key (dm_ctl_sha16, same as column 4 of shader_map.tsv) + "_b".
# Source of query answers: the in-repo answer table nvn/shader_facts.tsv (dmsh_facts.py) - texture types, vertex attribute / fragment output component types, compute thread group size and shared memory; the build needs no PC version files.
# Usage: dmsh_build.py <Switch package dir> <output cache dir> [key...] (no keys = all); build output is actually written to <output cache dir>/b-<chain version>/ (same for IOSOUT), for the chain version see dmsh_chain.py Environment: XLATE=path to the translation tool, DMSH_CAS=content-addressed cache dir (default <output cache dir>/cas), J=concurrency
# Graphics shaders embedded in the executable itself (mapping table rows main.rodata@offset) are extracted from MAIN (Switch main NSO, default 3.3.94012 Update/ExeFS/main); extracting the NSO needs lz4, run with dm's venv python
# Build output: <key>_b.metallib, <key>_b.json (replay reflection, including drv_reads, the runtime read offsets into driver segments c0 / c2), <key>_b.metal (MSL)
# Environment IOSOUT=dir: the same MSL also goes through dm/ios/tools/ios_metal.compile to produce an iphoneos metallib + reflection (chain_metal records the iOS compile convention)
# Final summary: success / failure counts and the distribution of reasons; distribution of driver segment read offsets (those outside the range the replay layer can fill are listed separately)
import ast, inspect, os, re, sys, json, struct, hashlib, shutil, subprocess, tempfile, collections, threading, concurrent.futures as cf
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
HOME = os.path.expanduser('~')
dm_dir, out = sys.argv[1:3]; want = set(sys.argv[3:]); cache_root = out
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))); import dmsh_chain, dmsh_fetch, dmsh_facts # 翻译链版本:先核工具与锁文件,产物进 b-<V>/ | translation chain version: verify the tools against the lock file first; build output goes into b-<V>/
_bad = dmsh_chain.check_tools()
if _bad: sys.exit('\n'.join('【红】翻译链工具与锁文件不符:' + b for b in _bad) + '\n(换了工具就 dmsh_chain.py --update-lock 并入仓;只是没重编翻译器就重编)')
CHAIN = dmsh_chain.version(); out = os.path.join(out, 'b-' + CHAIN)
if f'"{CHAIN}"' not in open(dmsh_chain.HEADER).read(): sys.exit(f'【红】nvn/dmsh_chain.h 不是当前翻译链版本 {CHAIN}:先跑 dmsh_chain.py --header(否则宿主找不到这批库)')
XLATE = os.environ.get('XLATE', f'{DM_ROOT}/build/gfx/dmsh_xlate/dmsh_xlate')
FACTS = dmsh_facts.load()
if not FACTS: sys.exit('【红】没有作答表 nvn/shader_facts.tsv(随仓库;维护者用 dmsh_facts.py --freeze 重出)')
IOSOUT = os.environ.get('IOSOUT') # 设了就同时出 iOS 版(iphoneos metallib + 反射)到该目录 | if set, also build the iOS version (iphoneos metallib + reflection) into that directory
if IOSOUT:
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../ios/tools')); import ios_metal
IOSOUT = os.path.join(IOSOUT, 'b-' + CHAIN); os.makedirs(IOSOUT, exist_ok=True)
MAIN = os.environ.get('MAIN', f'{DM_ROOT}/data/switch/3.3.94012/Update/ExeFS/main')
MAP = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../nvn/shader_map.tsv')
BF_WANT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../nvn/bf_want.tsv')
BF_WANT = {line.strip() for line in open(BF_WANT_FILE) if line.strip() and not line.lstrip().startswith('#')} if os.path.exists(BF_WANT_FILE) else set()
XC = ['--msl', '--msl-version', '20300', '--msl-argument-buffers', '--msl-texture-buffer-native', '--msl-pad-fragment-output']
CAS = os.environ.get('DMSH_CAS', os.path.join(cache_root, 'cas'))
CAS_LOCKS, CAS_LOCKS_GUARD = {}, threading.Lock()
PRE_STATS = collections.Counter()
MAC_RECORD = 'xcrun -sdk macosx metal -c; xcrun -sdk macosx metallib'
TEX_BASE, SAMP_BASE, IMG_BASE = 0x168, 0x568, 0x120 # c[2]:图像句柄表 0x120 + 8 r(8 槽,紧接贴图表之前;cs_lut_combine_c 写 u4 = 0x140 反推,u5 = 0x148 核对) | c[2]: image handle table 0x120 + 8 r (8 slots, immediately before the texture table; inferred from cs_lut_combine_c writing u4 = 0x140, checked with u5 = 0x148)
def records(d):
r = [m.start() for m in re.finditer(b'BTCDBTCD', d)]
return [d[x:(r[k + 1] if k + 1 < len(r) else len(d))] for k, x in enumerate(r)]
def clone(src, dst):
os.makedirs(os.path.dirname(dst), exist_ok=True)
tmp = dst + '.tmp-' + str(os.getpid()) + '-' + str(threading.get_ident())
r = subprocess.run(['cp', '-c', src, tmp], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=60)
if r.returncode:
shutil.copyfile(src, tmp)
os.replace(tmp, dst)
def atomic_json(path, value):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + '.tmp-' + str(os.getpid()) + '-' + str(threading.get_ident())
with open(tmp, 'w') as f: json.dump(value, f, ensure_ascii=False, indent=1)
os.replace(tmp, path)
def source_without_rule_bodies():
source = open(__file__, 'r').read(); lines = source.splitlines(True); tree = ast.parse(source)
names = {f.__name__ for f, _ in RULES}
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names and node.body:
first = node.body[0].lineno - 1
last = max(getattr(x, 'end_lineno', x.lineno) for x in ast.walk(node) if getattr(x, 'lineno', 0) >= node.body[0].lineno)
indent = re.match(r'\s*', lines[first]).group(0); lines[first:last] = [indent + 'pass\n']
return ''.join(lines)
def shader_rule_source(name):
return b''.join(inspect.getsource(f).encode() for f, applies in RULES if applies(name))
def tool_fingerprint():
sc = subprocess.run(['spirv-cross', '--version'], capture_output=True, text=True, timeout=30)
return ('lock\0' + open(dmsh_chain.LOCK).read() + '\0options\0' + dmsh_chain.options() +
'\0xlate\0' + dmsh_chain.xlate_source_sha() + '\0spirv-cross\0' + sc.stdout + sc.stderr +
'\0xc\0' + repr(XC) + '\0mac\0' + MAC_RECORD + '\0ios\0' + (ios_metal.RECORD if IOSOUT else ''))
def shader_key(key, name, rec):
pc = dmsh_facts.row(key, FACTS[key]).encode() if key in FACTS else '缺'.encode()
map_row = MAP_ROWS.get(key, '缺'.encode()) + MAP_CONFLICT_ROWS.get(key, b'')
embedded = rec if name.startswith('main.rodata@') else b''
payload = (b'record\0' + rec + b'\0map\0' + map_row + b'\0pc\0' + pc + b'\0embedded\0' + embedded +
b'\0tools\0' + TOOL_FP + b'\0code\0' + CODE_FP.encode() +
b'\0rule\0' + shader_rule_source(name))
return hashlib.sha256(payload).hexdigest()
def cache_meta_path(key): return os.path.join(CAS, 'index', key + '.json')
def cache_path(digest): return os.path.join(CAS, 'shader', digest)
def cache_outputs(key, digest, cached=False):
root = cache_path(digest); files = {}
for label, directory, names in (
('mac', out, [key + '_b.metallib', key + '_b.metal', key + '_b.json']),
('ios', IOSOUT, [key + '_b.metallib', key + '_b.json'])):
if not directory: continue
base = os.path.join(root, label) if cached else directory
found = [n for n in names if os.path.exists(os.path.join(base, n))]
if key + '_b.metallib' not in found or key + '_b.json' not in found: return None
files[label] = found
return root, files
def restore_cache(key, digest):
found = cache_outputs(key, digest, cached=True)
if not found: return False
root, files = found
for label, names in files.items():
directory = out if label == 'mac' else IOSOUT
for name in names:
src = os.path.join(root, label, name); dst = os.path.join(directory, name)
if name.endswith('.json'):
tmp = dst + '.tmp-' + str(os.getpid()) + '-' + str(threading.get_ident())
with open(tmp, 'wb') as f: f.write(re.sub(rb'("chain"\s*:\s*")[^"]*"', rb'\g<1>' + CHAIN.encode() + b'"', open(src, 'rb').read(), count=1))
os.replace(tmp, dst)
else: clone(src, dst)
return True
def cache_lookup(key, digest, rule_fp, code_fp):
with CAS_LOCKS_GUARD: lock = CAS_LOCKS.setdefault(('shader', key), threading.Lock())
with lock:
if restore_cache(key, digest): PRE_STATS['hit'] += 1; return True, '命中'
old = json.load(open(cache_meta_path(key))) if os.path.exists(cache_meta_path(key)) else None
if old and old.get('code_fp') != code_fp: reason = '代码指纹变化:全部重出'
elif old and old.get('rule_fp') != rule_fp: reason = '规则变'
else: reason = '新键'
PRE_STATS['miss'] += 1; PRE_STATS[reason] += 1; return False, reason
def publish_cache(key, digest, rule_fp, code_fp):
found = cache_outputs(key, digest)
if not found: return
root, files = found
for label, names in files.items():
d = os.path.join(root, label); os.makedirs(d, exist_ok=True)
for name in names: clone(os.path.join(out if label == 'mac' else IOSOUT, name), os.path.join(d, name))
for name in names:
if name.endswith('.json'):
src = os.path.join(out if label == 'mac' else IOSOUT, name)
value = json.load(open(src)); value.pop('fetch', None)
atomic_json(os.path.join(d, name), value)
atomic_json(cache_meta_path(key), {'digest': digest, 'rule_fp': rule_fp, 'code_fp': code_fp})
BF_STATS = collections.Counter()
def bf_digest(msl, key):
h = hashlib.sha256()
h.update(msl.encode())
h.update(b'\0mac\0' + MAC_RECORD.encode())
h.update(b'\0ios\0' + (ios_metal.RECORD if IOSOUT else '').encode())
h.update(b'\0bf-want\0' + (b'1' if key in BF_WANT else b'0'))
return h.hexdigest()
def bf_cache_root(digest): return os.path.join(CAS, 'variant', digest)
def bf_cache_restore(key, digest, fmeta, fmsl):
root = bf_cache_root(digest)
names = ['metal', 'mac.metallib'] + (['ios.metallib'] if IOSOUT else [])
if not all(os.path.exists(os.path.join(root, n)) for n in names): return False
clone(os.path.join(root, 'metal'), fmsl)
clone(os.path.join(root, 'mac.metallib'), os.path.join(out, key + '_bf.metallib'))
if IOSOUT: clone(os.path.join(root, 'ios.metallib'), os.path.join(IOSOUT, key + '_bf.metallib'))
BF_STATS['hit'] += 1
return True
def bf_cache_publish(digest, fmsl, maclib, ioslib, fmeta):
root = bf_cache_root(digest); os.makedirs(root, exist_ok=True)
clone(fmsl, os.path.join(root, 'metal'))
clone(maclib, os.path.join(root, 'mac.metallib'))
if IOSOUT: clone(ioslib, os.path.join(root, 'ios.metallib'))
atomic_json(os.path.join(root, 'fetch.json'), fmeta)
def write_refl(key, refl):
for d, rec in ((out, MAC_RECORD),) + (((IOSOUT, ios_metal.RECORD),) if IOSOUT else ()):
value = dict(refl, chain_metal=rec)
atomic_json(os.path.join(d, key + '_b.json'), value)
def fetch_finish(key, src, refl):
if refl['stage'] != 'ps': return refl
# 有可改采样的照旧出变体;没有可改采样的只给名单(bf_want.tsv,宿主规划器产出)里的键出仅输出映射变体
# Those with rewritable samples get variants as before; those without get an output-mapping-only variant, and only for keys in the list (bf_want.tsv, produced by the host planner)
fv, fmeta = dmsh_fetch.variant(src, refl['bindings'], om_only_ok=key in BF_WANT)
if not fv:
for path in (os.path.join(out, key + '_bf.metallib'), os.path.join(out, key + '_bf.metal')) + ((os.path.join(IOSOUT, key + '_bf.metallib'),) if IOSOUT else ()):
try: os.unlink(path)
except FileNotFoundError: pass
write_refl(key, refl)
return refl
BF_STATS['generated'] += 1
fmsl = os.path.join(out, key + '_bf.metal')
digest = bf_digest(fv, key)
with CAS_LOCKS_GUARD: lock = CAS_LOCKS.setdefault(('variant', digest), threading.Lock())
with lock:
try:
if not bf_cache_restore(key, digest, fmeta, fmsl):
BF_STATS['miss'] += 1
open(fmsl, 'w').write(fv)
fair = fmsl[:-6] + '.air'; flib = os.path.join(out, key + '_bf.metallib')
try:
subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '-c', fmsl, '-o', fair], check=True)
tmp_flib = flib + '.tmp-' + str(os.getpid())
subprocess.run(['xcrun', '-sdk', 'macosx', 'metallib', fair, '-o', tmp_flib], check=True)
os.replace(tmp_flib, flib)
ilib = None
if IOSOUT:
ilib = os.path.join(IOSOUT, key + '_bf.metallib')
ios_metal.compile(fmsl, fmsl[:-6] + '.ios.air', ilib + '.tmp')
os.replace(ilib + '.tmp', ilib)
except subprocess.CalledProcessError:
return refl
BF_STATS['compile'] += 1
bf_cache_publish(digest, fmsl, flib, ilib, fmeta)
finally:
for path in (fmsl, fmsl[:-6] + '.air', fmsl[:-6] + '.ios.air'):
try: os.unlink(path)
except FileNotFoundError: pass
refl['fetch'] = fmeta
write_refl(key, refl)
return refl
pc_of, loc, stage_of = {}, {}, {}
MAP_ROWS, MAP_CONFLICT_ROWS = {}, {}
for raw in open(MAP, 'rb'):
c = raw.rstrip(b'\n').split(b'\t')
if len(c) > 4: MAP_ROWS.setdefault(c[3].decode(), raw)
for raw in open(MAP + '.conflicts.tsv', 'rb'):
c = raw.rstrip(b'\n').split(b'\t')
if len(c) > 1 and not raw.startswith((b'#', b'dm_')): MAP_CONFLICT_ROWS.setdefault(c[0].decode(), raw)
for ln in open(MAP):
c = ln.rstrip('\n').split('\t')
if len(c) > 4 and c[0].endswith('.bin'): pc_of.setdefault(c[3], c[4]); loc.setdefault(c[3], (c[0], int(c[1])))
if len(c) > 4 and c[0].startswith('main.rodata@'): # 内嵌:位置 = main 映像偏移(控制段起点),阶段取映射表第 3 列 | embedded: location = main image offset (start of the control segment), stage taken from column 3 of the mapping table
pc_of.setdefault(c[3], c[4]); loc.setdefault(c[3], (c[0], int(c[0].split('@')[1], 16))); stage_of[c[3]] = {'顶点': 'vs', '像素': 'ps'}[c[2]]
for ln in open(MAP + '.conflicts.tsv'):
c = ln.rstrip('\n').split('\t')
if len(c) > 1 and not ln.startswith('#') and not ln.startswith('dm_') and c[0] in pc_of: pc_of[c[0]] = c[1]
def main_rec(mi, o):
"""内嵌着色器 → 与包内记录同布局的字节:包内记录 +0x38 起是代码区(0x30 头 + SPH + 指令,标记 78563412),紧接控制段(34127698);
内嵌的代码区紧贴在控制段之前(核对 5 个:代码区长 0x100–0x300、c1 均为空,与同名包内记录布局一致)
Embedded shader → bytes in the same layout as a package record: in a package record the code area starts at +0x38 (0x30 header + SPH + instructions, marker 78563412), immediately followed by the control segment (34127698);
the embedded code area sits immediately before the control segment (checked 5: code area length 0x100–0x300, c1 empty in all, consistent with the layout of the same-named package records)"""
g = mi.rfind(bytes.fromhex('78563412'), o - 0x1000, o)
if g < 0 or mi[o:o + 4] != bytes.fromhex('34127698'): sys.exit(f'【红】main 映像 @{o:#x} 不是内嵌着色器控制段(MAIN={MAIN})')
return bytes(0x38) + mi[g:o + 0x880]
def job_for(key, name, rec, w):
ci = rec.find(bytes.fromhex('34127698')); code = rec[0x38:ci]; stage = stage_of.get(key, name[:2])
c1o, c1t = struct.unpack_from('<2I', rec, ci + 0x700) # 控制段 +0x700:c1 相对指令区起点、+0x704:指令区总长(c1 = 两者之间;全库长度 0 / 256 / 512 / 768) | control segment +0x700: c1 relative to the start of the instruction area, +0x704: total length of the instruction area (c1 = what lies between the two; lengths across the whole library are 0 / 256 / 512 / 768)
c1 = rec[0x38 + c1o:0x38 + c1t]
if stage != 'cs': code = code[0x30:]
cp = os.path.join(w, key + '.bin'); open(cp, 'wb').write(code)
j = {'key': key, 'stage': stage, 'code': cp, 'tex': {}, 'img': {}, 'attr': {}, 'fout': {}, 'c1': c1.hex(),
'debug': os.environ.get('XLATE_DEBUG', '1') != '0', 'reduced': os.environ.get('XLATE_REDUCED', '1') == '1'} # 翻译选项(见 dmsh_xlate/Program.cs);放宽精度缺省开(GPU 浮点末位误差不进游戏状态,mini 整帧 −26%) # c1:翻译器读间接跳转表用 | translation options (see dmsh_xlate/Program.cs); relaxed precision is on by default (GPU float last-bit error does not enter game state, whole frame −26% on the second Mac) # c1: used by the translator to read indirect jump tables
if key not in FACTS: j['pc_missing'] = True; return j, c1 # 作答表里没有:查询按缺省(汇总里单列) | not in the answer table: queries use defaults (listed separately in the summary)
j.update(FACTS[key])
return j, c1
def raster_facts(stage, src):
"""读入可省(全覆盖首绘)的运行时证明所需的静态事实(nvn_mtl.m first_draw_covers):
顶点:位置 x / y / z 是否原样取自同一个顶点属性的 .x / .y / .z(w 为常数 1 或同属性 .w),主函数无分支、无裁剪距离——是则 pos_attr = 属性槽;
片元:是否可能丢弃(discard_fragment)、是否写 sample_mask、写出的颜色号。认不出一律按「不可证」(pos_attr = -1 / discard = 1)
Static facts needed for the runtime proof that the load can be skipped (full-coverage first draw) (nvn_mtl.m first_draw_covers):
Vertex: whether position x / y / z are taken unchanged from the .x / .y / .z of one and the same vertex attribute (w is the constant 1 or the same attribute's .w), with no branches and no clip distances in the main function - if so, pos_attr = attribute slot;
Fragment: whether it may discard (discard_fragment), whether it writes sample_mask, and which color indices it writes. Anything unrecognized is treated as "unprovable" (pos_attr = -1 / discard = 1)"""
if stage == 'ps':
out = re.search(r'struct main0_out\s*\{(.*?)\};', src, re.S)
return {'discard': int('discard_fragment' in src), 'sample_mask': int('sample_mask' in (out.group(1) if out else '')),
'colors': sorted({int(x) for x in re.findall(r'\[\[color\((\d+)\)\]\]', out.group(1) if out else '')})}
if stage != 'vs': return {}
body = re.search(r'\bvertex\s+\w+\s+\w+\s*\(.*?\)\s*\{(.*)\}\s*$', src, re.S) # 主函数是文件里最后一个函数 | the main function is the last function in the file
if not body or re.search(r'\b(if|for|while|switch|do)\b|clip_distance|ClipDistance', body.group(1)): return {'pos_attr': -1}
b = body.group(1)
attr = {m.group(2): int(m.group(3)) for m in re.finditer(r'(\w+)\s+(\w+)\s*\[\[attribute\((\d+)\)\]\]', src)}
var = {m.group(1): (m.group(2), m.group(3)) for m in re.finditer(r'float\s+(_\w+)\s*=\s*in\.(\w+)\.([xyzw]);', b)}
last = {}
for m in re.finditer(r'out\.gl_Position\.([xyzw])\s*=\s*([^;]+);', b): last[m.group(1)] = m.group(2).strip()
src_of = {c: var.get(v) for c, v in last.items()}
m0 = src_of.get('x')
if not m0 or m0[0] not in attr or any(src_of.get(c) != (m0[0], c) for c in 'xyz'): return {'pos_attr': -1}
if last.get('w') == '1.0': w = 'one'
elif src_of.get('w') == (m0[0], 'w'): w = 'attr'
else: return {'pos_attr': -1}
# uv 直传(合并 B 第 2 步「本像素寻址」证明用):插值输出 locn K 的 .x / .y 原样取自顶点属性 A 的 .x / .y → uv_from_attr[K] = A
# uv pass-through (used for the "this-pixel addressing" proof in merge B step 2): the .x / .y of interpolated output locn K are taken unchanged from the .x / .y of vertex attribute A → uv_from_attr[K] = A
ost = re.search(r'struct main0_out\s*\{(.*?)\};', src, re.S)
locn = {m.group(1): int(m.group(2)) for m in re.finditer(r'(m_\d+) \[\[user\(locn(\d+)\)\]\]', ost.group(1) if ost else '')}
olast = {}
for m in re.finditer(r'out\.(m_\d+)\.([xyzw])\s*=\s*([^;]+);', b): olast[(m.group(1), m.group(2))] = m.group(3).strip()
uv, aff = {}, {}
for mem, k in locn.items():
sx, sy = var.get(olast.get((mem, 'x'), '')), var.get(olast.get((mem, 'y'), ''))
if sx and sy and sx[0] == sy[0] and sx[0] in attr and sx[1] == 'x' and sy[1] == 'y': uv[str(k)] = attr[sx[0]]; continue
# 仿射:分量 = fma(属性分量, uniform[槽].向量[i].分量, uniform[槽].向量[j].分量)(vp_cN 即 uniform 槽 N − 3)
# Affine: component = fma(attribute component, uniform[slot].vector[i].component, uniform[slot].vector[j].component) (vp_cN is uniform slot N − 3)
def fm(v_):
m = re.search(r'float %s = fma\((_\w+), \(\*spvDescriptorSet0\.vp_c(\d+)\)\._m0\[(\d+)\]\.([xyzw]), \(\*spvDescriptorSet0\.vp_c(\d+)\)\._m0\[(\d+)\]\.([xyzw])\);' % re.escape(v_), b)
if not m or m.group(1) not in var: return None
return var[m.group(1)], [int(m.group(2)) - 3, int(m.group(3)), 'xyzw'.index(m.group(4))], [int(m.group(5)) - 3, int(m.group(6)), 'xyzw'.index(m.group(7))]
fx, fy = fm(olast.get((mem, 'x'), '')), fm(olast.get((mem, 'y'), ''))
if fx and fy and fx[0][0] == fy[0][0] and fx[0][0] in attr and fx[0][1] == 'x' and fy[0][1] == 'y' and min(fx[1][0], fx[2][0], fy[1][0], fy[2][0]) >= 0:
aff[str(k)] = {'attr': attr[fx[0][0]], 'sx': fx[1], 'ox': fx[2], 'sy': fy[1], 'oy': fy[2]}
return {'pos_attr': attr[m0[0]], 'pos_w': w, 'uv_from_attr': uv, 'uv_affine': aff}
def decode_tex(name):
"""fp_t_cb{slots}_{handle} / fp_t_tcb_{handle}:贴图槽、采样器槽(Ryujinx TextureHandle 编码;c[2] 句柄表) | fp_t_cb{slots}_{handle} / fp_t_tcb_{handle}: texture slot, sampler slot (Ryujinx TextureHandle encoding; c[2] handle table)"""
m = re.match(r'[a-z]+_[ti]\w*?_(?:cb(\d+)|tcb)_([0-9A-F]+)', name)
if not m: return None
slots = int(m.group(1)) if m.group(1) else -1; h = int(m.group(2), 16)
tb = (slots & 0xffff) if slots >= 0 else 2; sb = ((slots >> 16) - 1) if slots >= 0 and (slots >> 16) else tb
o0, o1, ty = h & 0x3fff, (h >> 14) & 0x3fff, h >> 28
def slot(word, base, cb): return (word * 4 - base) // 8 if cb == 2 and word * 4 >= base and (word * 4 - base) % 8 == 0 else None
words = [o0] + ([o1] if ty else [])
if re.match(r'[a-z]+_i', name): # 图像 | image
return next((slot(x, IMG_BASE, tb) for x in words if IMG_BASE <= x * 4 < TEX_BASE and slot(x, IMG_BASE, tb) is not None), None), None, ty
t = next((slot(x, TEX_BASE, tb) for x in words if slot(x, TEX_BASE, tb) is not None and x * 4 < SAMP_BASE), None)
s = next((slot(x, SAMP_BASE, sb) for x in words if x * 4 >= SAMP_BASE and slot(x, SAMP_BASE, sb) is not None), None)
return t, s, ty
def reflect(key, stage, msl, res):
"""MSL 参数缓冲结构体成员 → 回放反射:kind(同 nvn_refl.h)+ NVN 槽号 + 参数缓冲成员号 | MSL argument buffer struct member → replay reflection: kind (same as nvn_refl.h) + NVN slot number + argument buffer member index"""
body = re.search(r'struct spvDescriptorSetBuffer0\s*\{(.*?)\};', msl, re.S)
sb_cb = {b['binding']: b for b in res['sbufs']}
binds = []
for m in re.finditer(r'^\s*(.+?)\s+(\w+)\s*\[\[id\((\d+)\)\]\];', body.group(1) if body else '', re.M):
ty, nm, aid = m.group(1).strip(), m.group(2), int(m.group(3))
e = {'msl_name': nm, 'msl_type': ty, 'arg_id': aid}
if nm == 'support_buffer': e.update(kind='support')
elif re.fullmatch(r'[a-z]+_c(\d+)', nm):
n = int(re.fullmatch(r'[a-z]+_c(\d+)', nm).group(1))
e.update(kind='cbuf', reg=n - 3) if 3 <= n <= 16 else e.update(kind='c1' if n == 1 else 'drvcb', bank=n)
elif re.fullmatch(r'[a-z]+_s(\d+)', nm):
e.update(kind='sbuf', index=int(re.fullmatch(r'[a-z]+_s(\d+)', nm).group(1)))
elif nm.endswith('Smplr'): # 句柄类型 0 = 贴图与采样器合在同一句柄:采样器号取该贴图槽句柄的高位 | handle type 0 = texture and sampler combined in one handle: the sampler index is taken from the high bits of that texture slot's handle
t, s, ty = decode_tex(nm[:-5]); e.update(kind='samp', reg=s) if ty else e.update(kind='samp_tex', reg=t)
else:
d = decode_tex(nm)
if not d: e.update(kind='?')
else: e.update(kind='img' if re.match(r'[a-z]+_i', nm) else ('tbuf' if 'texture_buffer' in ty else 'tex'), reg=d[0])
binds.append(e)
# 存储缓冲:SPIR-V 绑定号 → c0 偏移 → NVN 存储缓冲槽(c0 基址:顶点 0x110、计算 0x310、像素 0x510,每槽 0x10)
# Storage buffers: SPIR-V binding number → c0 offset → NVN storage buffer slot (c0 base: vertex 0x110, compute 0x310, pixel 0x510, 0x10 per slot)
base = {'vs': 0x110, 'cs': 0x310, 'ps': 0x510}.get(stage) # 外壳 / 域阶段的存储缓冲基址未实测:遇到存储缓冲按「无槽」报 | storage buffer base for the hull / domain stages has not been measured: a storage buffer there is reported as 「无槽」(no slot)
sb_sorted = sorted(res['sbufs'], key=lambda b: b['binding'])
for e in binds:
if e['kind'] == 'sbuf':
b = sb_sorted[e['index']] if e['index'] < len(sb_sorted) else None
off = b['cb_offset'] * 4 if b and b['cb_slot'] == 0 else None
if stage == 'cs' and off is not None and 0x210 <= off < 0x310 and (off - 0x210) % 16 == 0:
e.update(kind='ubo_ptr', reg=(off - 0x210) // 16) # 计算阶段 uniform 槽 r:地址在 c0[0x210 + 0x10 r],经全局内存读(cs_lut_combine_c 读 cb10[66] 核对) | compute-stage uniform slot r: address at c0[0x210 + 0x10 r], read through global memory (checked against cs_lut_combine_c reading cb10[66])
else: e['reg'] = (off - base) // 16 if off is not None and base is not None and 0 <= off - base < 0x100 and (off - base) % 16 == 0 else None
e['rw'] = bool(b and b['flags'] & 2)
return binds
DRV_FILL = {0: [(0x110, 0x210), (0x310, 0x410), (0x510, 0x610)], # c0:存储缓冲地址表(顶点 / 计算 / 像素,各 16 槽 × 0x10) | c0: storage buffer address tables (vertex / compute / pixel, 16 slots × 0x10 each)
2: [(0x168, 0x568), (0x568, 0x968)]} # c2:贴图句柄表、采样器句柄表(各 128 槽 × 8) | c2: texture handle table, sampler handle table (128 slots × 8 each)
def drv_reads(src):
"""MSL 里对驱动段 c0 / c2 的读取:常量下标 → 字节区间;非常量下标记为动态 | Reads of driver segments c0 / c2 in the MSL: constant index → byte range; non-constant indices are recorded as dynamic"""
out = {}
for bank in (0, 2):
offs, dyn = set(), False
for m in re.finditer(r'fp_c%d\)\._m0\[([^\]]+)\]' % bank, src):
idx = m.group(1).rstrip('u')
if idx.isdigit(): offs.add(int(idx) * 16)
else: dyn = True
if offs or dyn: out[str(bank)] = {'vec4_offsets': sorted(offs), 'dynamic': dyn}
return out
def unfillable(dr):
bad = []
for bank, d in dr.items():
if d['dynamic']: bad.append(f'c{bank} 动态下标')
for o in d['vec4_offsets']:
if not any(a <= o and o + 16 <= b or (a <= o < b) for a, b in DRV_FILL[int(bank)]): bad.append(f'c{bank}+{o:#x}')
return bad
RULES = [] # 按着色器名挂的 MSL 改写规则(函数, 适用判定);原有的暗部重映射 toe 已删(回到 Switch 原版亮度) | MSL rewrite rules attached by shader name (function, applicability test); the former dark-range remap toe has been removed (back to the original Switch brightness)
# 第一段代码指纹不包含 dmsh_fetch.py;可读 tile 变体单独按生成 MSL 做第二段缓存。
# The first-stage code fingerprint does not include dmsh_fetch.py; readable-tile variants get a separate second-stage cache keyed on the generated MSL.
CODE_FP = hashlib.sha256(source_without_rule_bodies().encode() + b''.join(b'\0' + open(m.__file__, 'rb').read() for m in (dmsh_chain,) + ((ios_metal,) if IOSOUT else ()))).hexdigest()
TOOL_FP = tool_fingerprint().encode()
def finish(key, w, j, c1):
name, k = loc[key]
res = json.load(open(os.path.join(w, key + '.res.json')))
msl = os.path.join(w, key + '.metal'); air = msl[:-6] + '.air'; lib = os.path.join(out, key + '_b.metallib')
r = subprocess.run(['spirv-cross', *XC, os.path.join(w, key + '.spv'), '--output', msl], capture_output=True, text=True)
if r.returncode: return 'MSL 失败', r.stderr.strip()[:160], None
src = open(msl).read()
try:
subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '-c', msl, '-o', air], check=True)
tmp_lib = lib + '.tmp-' + str(os.getpid())
subprocess.run(['xcrun', '-sdk', 'macosx', 'metallib', air, '-o', tmp_lib], check=True)
os.replace(tmp_lib, lib)
except subprocess.CalledProcessError as e:
return 'metal 失败', str(e)[:160], None
clone(msl, os.path.join(out, key + '_b.metal'))
if IOSOUT: # iOS:同一份 MSL 走 iOS 的唯一编译口径(dm/ios/tools/ios_metal.py)出 iphoneos metallib | iOS: the same MSL goes through iOS's single compile convention (dm/ios/tools/ios_metal.py) to produce an iphoneos metallib
ilib = os.path.join(IOSOUT, key + '_b.metallib')
try:
ios_metal.compile(msl, msl[:-6] + '.ios.air', ilib + '.tmp')
os.replace(ilib + '.tmp', ilib)
except subprocess.CalledProcessError as e: return 'iOS metal 失败', str(e)[:160], None
entry = re.search(r'(vertex|fragment|kernel)\s+\S+\s+(\w+)\s*\(', src)
dr = drv_reads(src)
refl = {'key': key + '_b', 'route': 'B', 'chain': CHAIN, 'dm_ctl': key, 'source': f'{name}#{k}', 'pc_paired': pc_of[key], 'stage': j['stage'],
'entry': entry.group(2) if entry else 'main0', 'msl_entry_kind': entry.group(1) if entry else None,
'threadgroup_size': j.get('local'), 'c1': c1.hex(), 'notes': res['notes'] + (['无配对 PC 反射,查询按缺省'] if j.get('pc_missing') else []), 'drv_reads': dr, 'drv_unfillable': unfillable(dr),
'bindings': reflect(key, j['stage'], src, res),
'vertex_inputs': [{'location': int(m.group(2)), 'msl_type': m.group(1)} for m in re.finditer(r'(\w+)\s+\w+\s*\[\[attribute\((\d+)\)\]\]', src)],
'raster': raster_facts(j['stage'], src)}
write_refl(key, refl)
fetch_finish(key, src, refl)
return 'ok', '', refl
keys = sorted(want) if want else sorted(loc)
NJ = int(os.environ.get('J', '8'))
os.makedirs(out, exist_ok=True)
w = tempfile.mkdtemp(prefix='dmsh_', dir=os.environ.get('WORK'))
packs, jobs, c1s = {}, {}, {}
digests, rule_fps, cache_reasons, cache_hits = {}, {}, {}, set()
for key in keys:
name, k = loc[key]
if name.startswith('main.rodata@'):
if 'main' not in packs:
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../verify'))
try: import nsoimg
except ImportError as e: sys.exit(f'【红】解 main NSO 要 lz4({e}):用 $DM_ROOT/build/cache/dm/venv/bin/python 跑')
packs['main'] = nsoimg.load(MAIN)
rec = main_rec(packs['main'], k)
if hashlib.sha256(rec[rec.find(bytes.fromhex('34127698')):][:0x880]).hexdigest()[:16] != key: sys.exit(f'【红】{name} 控制段哈希与映射表键 {key} 不符(MAIN={MAIN})')
else:
if name not in packs: packs[name] = records(open(os.path.join(dm_dir, name), 'rb').read())
rec = packs[name][k]
digests[key] = shader_key(key, name, rec)
rule_fps[key] = hashlib.sha256(shader_rule_source(name)).hexdigest()
hit, cache_reasons[key] = cache_lookup(key, digests[key], rule_fps[key], CODE_FP)
if hit: cache_hits.add(key)
else: jobs[key], c1s[key] = job_for(key, name, rec, w)
misses = [key for key in keys if key not in cache_hits]
chunks = [misses[i::NJ] for i in range(NJ)]
def xl(ch):
jp = os.path.join(w, f'job_{abs(hash(ch[0]))}.json'); json.dump([jobs[k] for k in ch], open(jp, 'w'))
return subprocess.run([XLATE, jp, w], capture_output=True, text=True)
with cf.ThreadPoolExecutor(NJ) as ex: xr = list(ex.map(xl, [c for c in chunks if c]))
xerr = {}
for r in xr:
for ln in r.stderr.splitlines():
m = re.match(r'【红】(\w+):(.*)', ln)
if m: xerr[m.group(1)] = m.group(2)[:160]
def fin(key):
if key in cache_hits:
refl = json.load(open(os.path.join(out, key + '_b.json')))
src = open(os.path.join(out, key + '_b.metal')).read() if refl['stage'] == 'ps' else ''
return key, 'ok', '', fetch_finish(key, src, refl)
if key in xerr or not os.path.exists(os.path.join(w, key + '.spv')): return key, '翻译失败', xerr.get(key, '无 spv'), None
result = (key,) + finish(key, w, jobs[key], c1s[key])
if result[1] == 'ok': publish_cache(key, digests[key], rule_fps[key], CODE_FP)
return result
with cf.ThreadPoolExecutor(NJ) as ex: res = list(ex.map(fin, keys))
shutil.rmtree(w, ignore_errors=True)
st = collections.Counter(r[1] for r in res)
print(f'着色器 {len(res)}:成功 {st["ok"]},' + ','.join(f'{k} {v}' for k, v in st.items() if k != 'ok'))
print(f'前置缓存:命中 {PRE_STATS["hit"]},重出 {PRE_STATS["miss"]}')
for reason in ('新键', '规则变', '代码指纹变化:全部重出'):
if PRE_STATS[reason]: print(f' {reason} {PRE_STATS[reason]}')
print(f'变体缓存:生成 {BF_STATS["generated"]},命中 {BF_STATS["hit"]},重出 {BF_STATS["miss"]},编译 {BF_STATS["compile"]}')
for lvl in [k for k in st if k != 'ok']:
for e, n in collections.Counter(r[2] for r in res if r[1] == lvl).most_common(10): print(f' [{lvl}] {n:5d} {e}')
ok = [r[3] for r in res if r[1] == 'ok']
rd = [x for x in ok if x['drv_reads']]
print(f'运行时读驱动段的着色器 {len(rd)}(c0 {sum("0" in x["drv_reads"] for x in rd)},c2 {sum("2" in x["drv_reads"] for x in rd)});读到回放层填不了的 {sum(bool(x["drv_unfillable"]) for x in ok)}')
for e, n in collections.Counter(u for x in ok for u in x['drv_unfillable']).most_common(15): print(f' 填不了 {n:5d} {e}')
SLOTK = {'cbuf', 'samp', 'samp_tex', 'tex', 'img', 'tbuf', 'sbuf', 'ubo_ptr'}
noreg = [x for x in ok if any(b['kind'] in SLOTK and b.get('reg') is None for b in x['bindings'])]
unk = [x for x in ok if any(b['kind'] == '?' for b in x['bindings'])]
print(f'绑定没解出槽号的着色器 {len(noreg)},种类认不出的 {len(unk)}(运行时加载会报红)')
for e, n in collections.Counter(f"{b['kind']} {b['msl_name'][:28]}" for x in noreg + unk for b in x['bindings'] if b['kind'] == '?' or (b['kind'] in SLOTK and b.get('reg') is None)).most_common(8): print(f' {n:5d} {e}')
nt = collections.Counter(nn.split('(')[0] for x in ok for nn in x['notes'])
for e, n in nt.most_common(8): print(f' 查询无 PC 作答 {n:5d} {e}')
json.dump([{'key': r[0], 'st': r[1], 'err': r[2]} for r in res], open(os.path.join(out, '_b_build.json'), 'w'), ensure_ascii=False)
+8
View File
@@ -0,0 +1,8 @@
# 翻译链工具指纹(dmsh_chain.py --update-lock 生成;换工具后重生成并随提交入仓)
dmsh_xlate.dll aff3b70cff6bf29e
Ryujinx.Graphics.Shader.dll 72886c0b30bc0016
Ryujinx.Common.dll 614dced78b44547d
xlate_source 1cc46907ca1ee8d0
spirv-cross c95d3fc88f6ae5f5
metal_macosx Apple metal version 32023.883 (metalfe-32023.883)
metal_iphoneos Apple metal version 32023.883 (metalfe-32023.883)
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
# B 着色器库的翻译链版本(构建结果须只由源码决定)。
# 链版本 V = 下列仓内文件内容 + 翻译选项的 sha256 前 12 位:本脚本、dmsh_build.py、dmsh_fetch.py(可读 tile 版本)、dmsh_xlate 源(Program.cs、csproj)、
# 映射表(含冲突表)、翻译查询的作答表(dmsh_facts.py 与 nvn/shader_facts.tsv)、iOS 编译口径 ios_metal.py、工具锁 dmsh_chain.lock(Ryujinx 着色器 dll / spirv-cross / metal 编译器的实测指纹)。
# 出包(dmsh_build.py)写进 <缓存目录>/b-<V>/,反射 json 记 chain = V;宿主编译时取 nvn/dmsh_chain.h 里的 V,只从 b-<V>/ 加载并逐个核 json。
# 用法:dmsh_chain.py 打印 V(缺省选项)
# dmsh_chain.py --header 重写 nvn/dmsh_chain.h(改了上列任一文件后要跑,tests/t_chain.sh 核对)
# dmsh_chain.py --check-tools 核对实际工具与锁文件一致,不一致报红退出 1
# dmsh_chain.py --update-lock 按实际工具重写锁文件(换 Ryujinx / spirv-cross / Xcode 后跑,随提交入仓)
# 环境:XLATE_DEBUG / XLATE_REDUCED(与 dmsh_build.py 同义,缺省 1 / 1;非缺省选项得到不同的 V,宿主不会加载)
# Translation chain version of the B shader library (the build result must be determined by source alone).
# Chain version V = first 12 digits of the sha256 of the contents of the following in-repo files + the translation options: this script, dmsh_build.py, dmsh_fetch.py (readable-tile version), the dmsh_xlate sources (Program.cs, csproj),
# the mapping table (including the conflict table), the answer table for translation queries (dmsh_facts.py and nvn/shader_facts.tsv), the iOS compile convention ios_metal.py, the tool lock dmsh_chain.lock (measured fingerprints of the Ryujinx shader dll / spirv-cross / metal compiler).
# The build (dmsh_build.py) writes into <cache dir>/b-<V>/ and the reflection json records chain = V; at compile time the host takes V from nvn/dmsh_chain.h, loads only from b-<V>/ and verifies each json.
# Usage: dmsh_chain.py print V (default options)
# dmsh_chain.py --header rewrite nvn/dmsh_chain.h (run after changing any file listed above; tests/t_chain.sh verifies it)
# dmsh_chain.py --check-tools verify that the actual tools match the lock file; on mismatch report a failure and exit 1
# dmsh_chain.py --update-lock rewrite the lock file from the actual tools (run after changing Ryujinx / spirv-cross / Xcode; committed to the repo)
# Environment: XLATE_DEBUG / XLATE_REDUCED (same meaning as in dmsh_build.py, default 1 / 1; non-default options yield a different V, which the host will not load)
import os, sys, hashlib, subprocess
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
HERE = os.path.dirname(os.path.abspath(__file__)); GFX = os.path.dirname(HERE); HOME = os.path.expanduser('~')
FILES = ['tools/dmsh_chain.py', 'tools/dmsh_build.py', 'tools/dmsh_fetch.py', 'tools/dmsh_facts.py', 'nvn/shader_facts.tsv', 'tools/dmsh_xlate/Program.cs', 'tools/dmsh_xlate/dmsh_xlate.csproj',
'nvn/shader_map.tsv', 'nvn/shader_map.tsv.conflicts.tsv', '../ios/tools/ios_metal.py', 'tools/dmsh_chain.lock']
LOCK = os.path.join(HERE, 'dmsh_chain.lock'); HEADER = os.path.join(GFX, 'nvn/dmsh_chain.h')
XLATE_DIR = os.path.dirname(os.environ.get('XLATE', f'{DM_ROOT}/build/gfx/dmsh_xlate/dmsh_xlate'))
def options():
return 'debug=%s reduced=%s' % (os.environ.get('XLATE_DEBUG', '1') != '0', os.environ.get('XLATE_REDUCED', '1') == '1')
def version():
h = hashlib.sha256()
for f in FILES:
h.update(f.encode() + b'\0' + open(os.path.join(GFX, f), 'rb').read() + b'\0')
h.update(options().encode())
return h.hexdigest()[:12]
def sha16(p): return hashlib.sha256(open(p, 'rb').read()).hexdigest()[:16]
def tools_now():
"""实际工具指纹:翻译器 dll(含 Ryujinx 着色器库)、spirv-cross、metal 编译器(macOS / iOS) | Actual tool fingerprints: translator dll (including the Ryujinx shader library), spirv-cross, metal compiler (macOS / iOS)"""
t = {}
for dll in ('dmsh_xlate.dll', 'Ryujinx.Graphics.Shader.dll', 'Ryujinx.Common.dll'): t[dll] = sha16(os.path.join(XLATE_DIR, dll))
t['xlate_source'] = subprocess.run([os.path.join(XLATE_DIR, 'dmsh_xlate'), '--source-sha'], capture_output=True, text=True).stdout.strip()
sc = subprocess.run(['which', 'spirv-cross'], capture_output=True, text=True).stdout.strip()
t['spirv-cross'] = sha16(sc) if sc else 'missing'
for sdk in ('macosx', 'iphoneos'):
t['metal_' + sdk] = subprocess.run(['xcrun', '-sdk', sdk, 'metal', '--version'], capture_output=True, text=True).stdout.splitlines()[0:1] or ['missing']
t['metal_' + sdk] = t['metal_' + sdk][0]
return t
def xlate_source_sha(): # 与 dmsh_xlate --source-sha 同口径:嵌入的 Program.cs 与 csproj 依次拼接 | same convention as dmsh_xlate --source-sha: the embedded Program.cs and csproj concatenated in that order
return hashlib.sha256(b''.join(open(os.path.join(HERE, 'dmsh_xlate', f), 'rb').read() for f in ('Program.cs', 'dmsh_xlate.csproj'))).hexdigest()[:16]
def check_tools():
want = dict(l.rstrip('\n').split('\t', 1) for l in open(LOCK) if '\t' in l and not l.startswith('#'))
now = tools_now(); bad = [f'{k}:锁 {want.get(k)} / 实际 {v}' for k, v in now.items() if want.get(k) != v]
if now['xlate_source'] != xlate_source_sha(): bad.append(f'翻译器不是用仓内源编的:嵌入源 {now["xlate_source"]} / 仓内 {xlate_source_sha()}(重编 dmsh_xlate)')
return bad
if __name__ == '__main__':
a = sys.argv[1:]
if a == ['--update-lock']:
t = tools_now()
if t['xlate_source'] != xlate_source_sha(): sys.exit(f'【红】翻译器不是用仓内源编的(嵌入 {t["xlate_source"]} / 仓内 {xlate_source_sha()}):先重编 dmsh_xlate')
open(LOCK, 'w').write('# 翻译链工具指纹(dmsh_chain.py --update-lock 生成;换工具后重生成并随提交入仓)\n' + ''.join(f'{k}\t{v}\n' for k, v in t.items()))
print('已写', LOCK)
elif a == ['--check-tools']:
bad = check_tools()
for b in bad: print('【红】翻译链工具与锁文件不符:' + b)
sys.exit(1 if bad else 0)
elif a == ['--header']:
open(HEADER, 'w').write('// 生成文件(dm/gfx/tools/dmsh_chain.py --header):本源码树期望的 B 着色器库翻译链版本(缺省选项);宿主只加载 <库目录>/b-<V>/\n'
f'#define DMSH_CHAIN "{version()}"\n')
print(version())
elif not a: print(version())
else: sys.exit(__doc__ if __doc__ else '用法见文件头')
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
# B 路线全库干转:Switch 着色器包每个变体(按控制段哈希去重)→ Ryujinx ShaderTools 出 SPIR-V → spirv-cross 出 MSL → metal 编译。
# 逐级记成败与报错首行,汇总成功率与失败原因分布。干转用 ShaderTools 缺省查询(贴图类型等未按真实作答),只量「能不能转」。
# 用法:dmsh_dryrun.py <Switch 包目录> <ShaderTools 可执行> <输出目录> 环境 J=并发
# Route B whole-library dry run: every variant in the Switch shader packages (deduplicated by control segment hash) → SPIR-V via Ryujinx ShaderTools → MSL via spirv-cross → metal compile.
# Records pass/fail and the first error line at each stage, and summarizes the success rate and the distribution of failure reasons. The dry run uses ShaderTools' default queries (texture types etc. are not answered truthfully) and only measures "can it be converted".
# Usage: dmsh_dryrun.py <Switch package dir> <ShaderTools executable> <output dir> Environment J=concurrency
import os, re, sys, json, hashlib, subprocess, struct, tempfile, collections, concurrent.futures as cf
dm_dir, shtools, out = sys.argv[1:4]
os.makedirs(out, exist_ok=True)
XC = ['--msl', '--msl-version', '20300', '--msl-argument-buffers', '--msl-texture-buffer-native']
def records(d):
r = [m.start() for m in re.finditer(b'BTCDBTCD', d)]
return [d[x:(r[k + 1] if k + 1 < len(r) else len(d))] for k, x in enumerate(r)]
def first_err(s):
for ln in s.splitlines():
if 'error' in ln.lower() or 'exception' in ln.lower(): return re.sub(r'/[^ :]*/', '', ln.strip())[:160]
return (s.strip().splitlines() or ['(无输出)'])[-1][:160]
def one(job):
key, name, comp, code = job
with tempfile.TemporaryDirectory() as w:
bi, spv, msl, air = (os.path.join(w, n) for n in ('c.bin', 'c.spv', 'c.metal', 'c.air'))
open(bi, 'wb').write(code)
r = subprocess.run([shtools, '--target-language', 'Spirv', '--target-api', 'Vulkan'] + (['--compute'] if comp else []) + [bi, spv], capture_output=True, text=True)
if r.returncode or not os.path.exists(spv) or os.path.getsize(spv) == 0: return key, name, 'spirv', first_err(r.stdout + r.stderr)
r = subprocess.run(['spirv-cross', *XC, spv, '--output', msl], capture_output=True, text=True)
if r.returncode: return key, name, 'msl', first_err(r.stdout + r.stderr)
r = subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '-c', msl, '-o', air], capture_output=True, text=True)
if r.returncode: return key, name, 'metal', first_err(r.stdout + r.stderr)
return key, name, 'ok', ''
jobs, seen = [], set()
for name in sorted(os.listdir(dm_dir)):
if not name.endswith('.bin'): continue
for b in records(open(os.path.join(dm_dir, name), 'rb').read()):
ci = b.find(bytes.fromhex('34127698')); csz = struct.unpack_from('<I', b, 0x28)[0]
key = hashlib.sha256(b[ci:ci + csz]).hexdigest()[:16]
if key in seen: continue
seen.add(key); comp = name.startswith('cs_'); code = b[0x38:ci]
jobs.append((key, name, comp, code if comp else code[0x30:]))
with cf.ThreadPoolExecutor(int(os.environ.get('J', '8'))) as ex: res = list(ex.map(one, jobs))
json.dump(res, open(os.path.join(out, 'dryrun.json'), 'w'), ensure_ascii=False, indent=0)
st = collections.Counter(r[2] for r in res)
print(f'去重后着色器 {len(res)}:成功 {st["ok"]}({st["ok"] / len(res):.1%}),SPIR-V 失败 {st["spirv"]},MSL 失败 {st["msl"]},metal 编译失败 {st["metal"]}')
for lvl in ('spirv', 'msl', 'metal'):
c = collections.Counter(r[3] for r in res if r[2] == lvl)
for e, n in c.most_common(12): print(f' [{lvl}] {n:5d} {e}')
byf = collections.Counter(r[1] for r in res if r[2] == lvl)
if byf: print(f' [{lvl}] 按文件:', dict(byf.most_common(12)))
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
# 翻译查询的作答表 nvn/shader_facts.tsv:每个 Switch 着色器键一行,记翻译器问得到、但 Switch 机器码里读不出的那几项事实——
# 贴图 / 图像的维度类型、图像格式、顶点属性与片元输出的分量类型、计算着色器的线程组大小与共享内存字节数。
# 这些事实取自与它一一配对的 PC 版着色器的反射(NVN 槽号 = D3D 寄存器号,见 dm/gfx/README.md)。表随仓库,出着色器库只读这张表,
# 不需要 PC 版游戏文件;表里没有的键,翻译查询按缺省作答(出包汇总里单列)。
# 用法:dmsh_facts.py --freeze 从 PC 反射重出整张表(维护者用;要 PCCACHE 反射目录、PC DXBC 目录与 vkd3d-compiler)
# dmsh_facts.py --check 重算一遍与仓内的表逐键比对,不一致报红退出 1(同上,要 PC 侧输入)
# dmsh_facts.py 打印表的行数与各项事实的覆盖数
# 行格式:键 <TAB> JSON(键按字典序、紧凑写法;同样的输入逐字节同样的表)
# Answer table for translation queries, nvn/shader_facts.tsv: one row per Switch shader key, recording the few facts the translator asks for but that cannot be read from the Switch machine code -
# dimension type of textures / images, image format, component types of vertex attributes and fragment outputs, thread group size and shared memory bytes of compute shaders.
# These facts come from the reflection of the PC shader paired one-to-one with it (NVN slot number = D3D register number, see dm/gfx/README.md). The table ships with the repo; building the shader library reads only this table
# and needs no PC game files; for keys not in the table, translation queries are answered with defaults (listed separately in the build summary).
# Usage: dmsh_facts.py --freeze regenerate the whole table from PC reflection (for maintainers; needs the PCCACHE reflection dir, the PC DXBC dir and vkd3d-compiler)
# dmsh_facts.py --check recompute and compare key by key against the in-repo table; on mismatch report a failure and exit 1 (as above, needs the PC-side inputs)
# dmsh_facts.py print the table's row count and the coverage count of each fact
# Row format: key <TAB> JSON (keys in lexicographic order, compact form; the same input gives a byte-identical table)
import json, os, re, subprocess, sys
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
HERE = os.path.dirname(os.path.abspath(__file__)); HOME = os.path.expanduser('~')
TABLE = os.path.join(HERE, '../nvn/shader_facts.tsv'); MAP = os.path.join(HERE, '../nvn/shader_map.tsv')
TT = {'texture1d': '1d', 'texture1darray': '1darray', 'texture2d': '2d', 'texture2darray': '2darray', 'texture2dms': '2dms',
'texture2dmsarray': '2dmsarray', 'texture3d': '3d', 'texturecube': 'cube', 'texturecubearray': 'cubearray', 'buffer_typed': 'buffer'}
CT = {'float': 'float', 'int': 'sint', 'uint': 'uint'}
def load():
"""键 → 事实字典;表不存在返回空字典 | key → fact dict; returns an empty dict if the table does not exist"""
if not os.path.exists(TABLE): return {}
return {k: json.loads(v) for k, v in (l.rstrip('\n').split('\t', 1) for l in open(TABLE) if l.strip() and not l.startswith('#'))}
def row(key, facts): return key + '\t' + json.dumps(facts, sort_keys=True, separators=(',', ':'), ensure_ascii=False) + '\n'
def from_pc(pj, stage, dxbc_asm):
"""PC 反射 json(pj)+ 计算着色器的 DXBC 反汇编文本(没有给 None)→ 事实字典 | PC reflection json (pj) + DXBC disassembly text of the compute shader (None if absent) → fact dict"""
f = {'tex': {}, 'img': {}, 'attr': {}, 'fout': {}}
for b in pj['bindings']:
if b['kind'] == 't' and b['type'] in TT: f['tex'][str(b['reg'])] = TT[b['type']]
if b['kind'] == 'u' and b['type'] in TT:
f['img'][str(b['reg'])] = {'type': TT[b['type']], 'fmt': 'R32Uint' if 'uint' in (b.get('msl_type') or '') else 'R16G16B16A16Float'}
for v in pj.get('vertex_inputs') or []: f['attr'][str(v.get('location', v.get('index')))] = CT.get(v.get('component_type'), 'float')
for o in pj.get('fragment_outputs') or []: f['fout'][str(o.get('index', 0))] = CT.get(o.get('component_type'), 'float')
if pj.get('threadgroup_size'): f['local'] = pj['threadgroup_size']
if stage == 'cs': # 共享内存:PC DXBC 的 groupshared 声明求和(翻译器缺省 48 KB,超 Metal 上限 32 KB) | shared memory: sum of the groupshared declarations in the PC DXBC (the translator default is 48 KB, over Metal's 32 KB limit)
asm = dxbc_asm or ''
n = sum(int(m.group(1)) for m in re.finditer(r'dcl_tgsm_raw\s+g\d+,\s*(\d+)', asm)) + \
sum(int(m.group(1)) * int(m.group(2)) for m in re.finditer(r'dcl_tgsm_structured\s+g\d+,\s*(\d+),\s*(\d+)', asm))
f['shared'] = (n + 15) // 16 * 16
if dxbc_asm is None: f['pc_missing'] = True
return f
def pairs():
"""映射表(含冲突表的改判)→ {键: (配对的 PC 名, 阶段)} | Mapping table (with the conflict table's overrides) → {key: (paired PC name, stage)}"""
pc_of, stage_of = {}, {}
for ln in open(MAP):
c = ln.rstrip('\n').split('\t')
if len(c) > 4 and c[0].endswith('.bin'): pc_of.setdefault(c[3], c[4]); stage_of.setdefault(c[3], c[0][:2])
if len(c) > 4 and c[0].startswith('main.rodata@'): pc_of.setdefault(c[3], c[4]); stage_of[c[3]] = {'顶点': 'vs', '像素': 'ps'}[c[2]]
for ln in open(MAP + '.conflicts.tsv'):
c = ln.rstrip('\n').split('\t')
if len(c) > 1 and not ln.startswith('#') and not ln.startswith('dm_') and c[0] in pc_of: pc_of[c[0]] = c[1]
return {k: (pc_of[k], stage_of[k]) for k in pc_of}
def recompute():
pcc = os.environ.get('PCCACHE', f'{DM_ROOT}/build/cache/metal_shader_cache')
dxdirs = os.environ.get('PCDXBC', f'{DM_ROOT}/build/ios/dxbc_all_0930:{DM_ROOT}/data/d3d12_study/shaders').split(':')
vk = os.environ.get('VKD3D', f'{DM_ROOT}/build/vkd3d/inst/bin/vkd3d-compiler')
if not os.path.isdir(pcc): sys.exit(f'【红】没有 PC 反射目录 {pcc}(PCCACHE=)')
out, missing = {}, 0
for key, (pc, stage) in sorted(pairs().items()):
pp = os.path.join(pcc, pc + '.json')
if not os.path.exists(pp): missing += 1; continue # 无配对 PC 反射:不进表,查询按缺省 | no paired PC reflection: not entered in the table, queries use defaults
asm = None
if stage == 'cs':
dx = next((p for d in dxdirs for p in (os.path.join(d, pc + '.dxbc'), os.path.join(d, pc[:12] + '.dxbc')) if os.path.exists(p)), None)
if dx: asm = subprocess.run([vk, '-x', 'dxbc-tpf', '-b', 'd3d-asm', dx], capture_output=True, text=True).stdout
out[key] = from_pc(json.load(open(pp)), stage, asm)
return out, missing
if __name__ == '__main__':
a = sys.argv[1:]
if a == ['--freeze']:
t, missing = recompute()
open(TABLE, 'w').write('# 翻译查询的作答表(dmsh_facts.py --freeze 生成,勿手改):键 <TAB> 事实 JSON\n' + ''.join(row(k, t[k]) for k in sorted(t)))
print(f'已写 {TABLE}:{len(t)} 键;无配对 PC 反射、未进表 {missing}')
elif a == ['--check']:
t, missing = recompute(); have = load()
bad = sorted(k for k in set(t) | set(have) if t.get(k) != have.get(k))
for k in bad[:10]: print(f'【红】{k}:表 {have.get(k)} / 重算 {t.get(k)}')
print(f'逐键比对 {len(set(t) | set(have))}:不一致 {len(bad)};无配对 PC 反射 {missing}'); sys.exit(1 if bad else 0)
elif not a:
t = load(); print(f'{len(t)} 键:' + ','.join(f'{n} {sum(bool(f.get(n)) for f in t.values())}' for n in ('tex', 'img', 'attr', 'fout', 'local', 'shared', 'pc_missing')))
else: sys.exit('用法见文件头')
+64
View File
@@ -0,0 +1,64 @@
# 片元着色器的「可读 tile」版本(合并 B 第 2 步):同一通道里,后一次绘制本像素采样前一次绘制写的颜色附件时,
# 改成直接读 tile 内的颜色(framebuffer fetch),两个渲染通道合成一个,中间附件不必为被采样而落主存再读回。
# 离线出包、运行时只做函数常量特化(不编译源码)。用法:variant(msl, bindings, om_only_ok=False) → (新 MSL, 元数据) 或 (None, 原因)
# 函数常量编号:FX_i(第 i 次可改采样读第几号颜色,-1 = 照常采样)= i;FB_k(启用第 k 号颜色输入)= 32 + k;
# OM_j_k(第 j 个输出写到第 k 号附件)= 64 + 8 j + k
# 可改的采样:2D 浮点贴图的 .sample(采样器, select(_N, float2(0.0), isnan(_N))),且 _N = float2(in.m_X.x, in.m_X.y)(插值输出原样);
# 是否真在本像素取纹素由运行时证明(顶点 uv 与位置的对应、贴图尺寸 = 目标尺寸),证不出就用原版本
# "Readable-tile" version of a fragment shader (merge B step 2): within one pass, when a later draw samples, at its own pixel, a color attachment written by an earlier draw,
# it is changed to read the color directly from the tile (framebuffer fetch); the two render passes become one, and the intermediate attachment need not be stored to main memory and loaded back just to be sampled.
# Built offline; at runtime only function-constant specialization is done (no source compilation). Usage: variant(msl, bindings, om_only_ok=False) → (new MSL, metadata) or (None, reason)
# Function constant numbering: FX_i (which color index the i-th rewritable sample reads, -1 = sample as usual) = i; FB_k (enable color input k) = 32 + k;
# OM_j_k (the j-th output writes to attachment k) = 64 + 8 j + k
# Rewritable samples: .sample(sampler, select(_N, float2(0.0), isnan(_N))) on a 2D float texture, where _N = float2(in.m_X.x, in.m_X.y) (interpolated output unchanged);
# whether the texel is really fetched at this pixel is proven at runtime (correspondence between vertex uv and position, texture size = target size); if it cannot be proven, the original version is used
import re
NFB = 8
def variant(msl, bindings, om_only_ok=False):
tex = {m.group(1) for m in re.finditer(r'texture2d<float> (\w+) \[\[id\(\d+\)\]\];', msl)}
locn = {m.group(1): int(m.group(2)) for m in re.finditer(r'float4 (m_\d+) \[\[user\(locn(\d+)\)\]\];', msl.split('struct main0_in', 1)[-1].split('};', 1)[0])}
reg = {b['msl_name']: b['reg'] for b in bindings if b.get('kind') == 'tex' and b.get('msl_name') and b.get('reg') is not None}
pat = re.compile(r'spvDescriptorSet0\.(\w+)\.sample\(spvDescriptorSet0\.(\w+)Smplr, select\((_\d+), float2\(0\.0\), isnan\(\3\)\)\)')
calls, out_parts, pos = [], [], 0
for m in pat.finditer(msl):
member, var = m.group(1), m.group(3)
if member not in tex or member != m.group(2) or member not in reg: continue
d = re.search(r'float2 %s = float2\((_\d+), (_\d+)\);' % var, msl)
a = d and re.search(r'float %s = in\.(m_\d+)\.x;' % d.group(1), msl); b = d and re.search(r'float %s = in\.(m_\d+)\.y;' % d.group(2), msl)
if not (a and b) or a.group(1) != b.group(1) or a.group(1) not in locn: continue
i = len(calls)
if i >= 32: break
sel = ''.join(f'FX_{i} == {k} ? fb{k} : ' for k in range(NFB))
out_parts.append(msl[pos:m.start()]); out_parts.append(f'({sel}{m.group(0)})'); pos = m.end()
calls.append({'fc': i, 'tex_reg': reg[member], 'varying_locn': locn[a.group(1)]})
if not calls and not om_only_ok:
return None, '没有可改的采样'
# 混用的槽:同一贴图还有别的(不可改的)用法——运行时不得把这张贴图改成读 tile(改了的几次与没改的读到的会不是同一份数据)
# Mixed-use slots: the same texture also has other (non-rewritable) uses - at runtime this texture must not be switched to tile reads (the rewritten reads and the unrewritten ones would not see the same data)
conv = {}
for c in calls: conv[c['tex_reg']] = conv.get(c['tex_reg'], 0) + 1
mixed = sorted({reg[mb] for mb in reg if mb in tex and msl.count(f'spvDescriptorSet0.{mb}.') > conv.get(reg[mb], 0)})
body = ''.join(out_parts) + msl[pos:]
om = re.search(r'struct main0_out\s*\{(.*?)\};', body, re.S)
if not om: return None, '没有输出结构'
outs = [(t, n, int(c)) for t, n, c in re.findall(r'(\w+) (m_\d+) \[\[color\((\d+)\)\]\];', om.group(1))]
if not outs or len(outs) > 4 or re.sub(r'\w+ m_\d+ \[\[color\(\d+\)\]\];', '', om.group(1)).strip(): return None, '输出结构不是单纯的颜色输出(或超过 4 个)'
members = ''.join(f' {t} {n}_at{k} [[color({k}), function_constant(OM_{j}_{k})]];\n' for j, (t, n, c) in enumerate(outs) for k in range(NFB))
body = body[:om.start(1)] + '\n' + members + body[om.end(1):]
consts = ''.join(f'constant int FX_{c["fc"]} [[function_constant({c["fc"]})]];\n' for c in calls) + \
''.join(f'constant bool FB_{k} [[function_constant({32 + k})]];\n' for k in range(NFB)) + \
''.join(f'constant bool OM_{j}_{k} [[function_constant({64 + 8 * j + k})]];\n' for j in range(len(outs)) for k in range(NFB))
body = body.replace('using namespace metal;\n', 'using namespace metal;\n\n' + consts, 1)
i0 = body.find('fragment main0_out main0(')
i1 = body.find(')\n{', i0) if i0 >= 0 else -1 # 签名结尾:右括号后紧跟换行与左花括号(参数属性里有 [[buffer(0)]] 等括号) | end of signature: closing parenthesis immediately followed by a newline and an opening brace (parameter attributes contain brackets such as [[buffer(0)]])
if i0 < 0 or i1 < 0: return None, '主函数签名认不出'
body = body[:i1] + ''.join(f', float4 fb{k} [[color({k}), function_constant(FB_{k})]]' for k in range(NFB)) + body[i1:]
decl = ''.join(f' {t} spv_o_{n} = {t}(0);\n' for t, n, c in outs)
body = body.replace(' main0_out out = {};\n', ' main0_out out = {};\n' + decl, 1)
for t, n, c in outs: body = body.replace(f'out.{n}', f'spv_o_{n}')
put = ''.join(f' if (OM_{j}_{k}) out.{n}_at{k} = spv_o_{n};\n' for j, (t, n, c) in enumerate(outs) for k in range(NFB))
if body.count(' return out;\n') < 1: return None, '找不到 return out'
body = body.replace(' return out;\n', put + ' return out;\n')
return body, {'calls': calls, 'mixed_regs': mixed, 'outputs': [{'color': c, 'type': t} for t, n, c in outs]}
+143
View File
@@ -0,0 +1,143 @@
// Switch 原版着色器(Maxwell 机器码)→ SPIR-V(Ryujinx.Graphics.Shader 翻译器),供 B 路线离线出 metallib。
// 与 Ryujinx.ShaderTools 的区别:翻译器的「查询」按真实情况作答,而不是一律缺省值——
// 贴图类型 / 图像格式 / 顶点属性类型 / 片元输出类型 / 计算线程组大小取自作业文件(由映射表配对的 PC 反射给出,同槽号 = 同资源);
// 窗口原点左上、深度 0..1(游戏实测 nvnDeviceSetWindowOriginMode / SetDepthMode)。
// 用法:dmsh_xlate <作业.json> <输出目录>
// 作业:[{ "key", "stage": "vs|ps|cs", "code": 机器码文件(图形 = 0x50 字节 SPH + 指令,计算 = 指令),
// "tex": { "槽": "2d|2darray|cube|cubearray|3d|buffer|1d|1darray|2dms|2dmsarray", … }, "img": { "槽": { "type", "fmt" } },
// "attr": { "位置": "float|sint|uint" }, "fout": { "目标": "float|sint|uint" }, "local": [x, y, z] }]
// 输出:<key>.spv 与 <key>.res.json(存储缓冲槽在 c0 的偏移等,贴图句柄 → 槽号的解码在出 metallib 的脚本里做)
// Original Switch shaders (Maxwell machine code) → SPIR-V (the Ryujinx.Graphics.Shader translator), for route B's offline metallib build.
// Difference from Ryujinx.ShaderTools: the translator's "queries" are answered truthfully rather than always with defaults -
// texture type / image format / vertex attribute type / fragment output type / compute thread group size come from the job file (given by the PC reflection paired via the mapping table; same slot number = same resource);
// window origin upper-left, depth 0..1 (measured from the game: nvnDeviceSetWindowOriginMode / SetDepthMode).
// Usage: dmsh_xlate <job.json> <output dir>
// Job: [{ "key", "stage": "vs|ps|cs", "code": machine code file (graphics = 0x50-byte SPH + instructions, compute = instructions),
// "tex": { "slot": "2d|2darray|cube|cubearray|3d|buffer|1d|1darray|2dms|2dmsarray", ... }, "img": { "slot": { "type", "fmt" } },
// "attr": { "location": "float|sint|uint" }, "fout": { "target": "float|sint|uint" }, "local": [x, y, z] }]
// Output: <key>.spv and <key>.res.json (offsets of storage buffer slots in c0, etc.; decoding texture handle → slot number is done in the script that builds the metallib)
using Ryujinx.Common.Memory;
using Ryujinx.Graphics.Shader;
using Ryujinx.Graphics.Shader.Translation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Nodes;
static class SwshXlate
{
const int TexBase = 0x168, SampBase = 0x568; // NVN 分离贴图 / 采样器句柄在 c[2] 的字节基址(每槽 8 字节;dm/gfx/tools/maxwell_refs.py 全量实测) | byte base of NVN separate texture / sampler handles in c[2] (8 bytes per slot; full measurement in dm/gfx/tools/maxwell_refs.py)
sealed class Accessor : IGpuAccessor
{
readonly byte[] _code; readonly JsonObject _job; int _binding = 1; public readonly List<string> Notes = new();
readonly byte[] _c1;
public Accessor(byte[] code, JsonObject job) { _code = code; _job = job; _c1 = job["c1"] is JsonNode h ? Convert.FromHexString((string)h) : Array.Empty<byte>(); }
// c1 常数段(着色器包控制段前 0x100 字节):间接跳转 BRX 的跳转表在这里(LDC c[1]);不提供时翻译器解不出跳转目标、控制流出错(粒子着色器死循环)
// c1 constant segment (the 0x100 bytes before the control segment in the shader package): the jump table of indirect jump BRX lives here (LDC c[1]); without it the translator cannot resolve jump targets and control flow goes wrong (particle shaders loop forever)
public uint ConstantBuffer1Read(int offset) { if (offset >= 0 && offset + 4 <= _c1.Length) return BitConverter.ToUInt32(_c1, offset); Notes.Add($"c1 读越界 +{offset:X}(c1 长 {_c1.Length})"); return 0; }
// 全部资源放进第 0 组,各占不同绑定号(spirv-cross 出成一个参数缓冲);常量段号 index 的缓冲由翻译器给 binding = index+1 的惯例不依赖
// All resources go into set 0, each with a distinct binding number (spirv-cross emits them as one argument buffer); the translator's convention of giving the buffer of constant segment number index binding = index+1 is not relied on
public SetBindingPair CreateConstantBufferBinding(int index) => new(0, _binding++);
public SetBindingPair CreateImageBinding(int count, bool isBuffer) { int b = _binding; _binding += count; return new(0, b); }
public SetBindingPair CreateStorageBufferBinding(int index) => new(0, _binding++);
public SetBindingPair CreateTextureBinding(int count, bool isBuffer) { int b = _binding; _binding += count; return new(0, b); }
public ReadOnlySpan<ulong> GetCode(ulong address, int minimumSize) => MemoryMarshal.Cast<byte, ulong>(new ReadOnlySpan<byte>(_code)[(int)address..]);
public int QuerySamplerArrayLengthFromPool() => 32;
public int QueryTextureArrayLengthFromBuffer(int slot) => 32;
public int QueryTextureArrayLengthFromPool() => 32;
string Get(string table, int slot) => _job[table] is JsonObject t && t[slot.ToString()] is JsonNode n ? (n is JsonObject o ? (string)o["type"] : (string)n) : null;
int TexSlot(int handle, int cbufSlot)
{
(int off0, _, _) = TextureHandle.UnpackOffsets(handle);
int bytes = off0 * 4;
return (cbufSlot < 0 || (cbufSlot & 0xffff) == 2) && bytes >= TexBase && bytes < SampBase && (bytes - TexBase) % 8 == 0 ? (bytes - TexBase) / 8 : -1;
}
public SamplerType QuerySamplerType(int handle, int cbufSlot = -1)
{
int slot = TexSlot(handle, cbufSlot);
string t = slot >= 0 ? Get("tex", slot) ?? Get("img", slot) : null;
if (t == null) { Notes.Add($"贴图句柄 {handle:X}(常量段 {cbufSlot},槽 {slot})无 PC 类型,按 2D"); return SamplerType.Texture2D; }
return t switch
{
"1d" => SamplerType.Texture1D, "1darray" => SamplerType.Texture1D | SamplerType.Array,
"buffer" => SamplerType.TextureBuffer, "2d" => SamplerType.Texture2D, "2darray" => SamplerType.Texture2D | SamplerType.Array,
"2dms" => SamplerType.Texture2D | SamplerType.Multisample, "2dmsarray" => SamplerType.Texture2D | SamplerType.Multisample | SamplerType.Array,
"3d" => SamplerType.Texture3D, "cube" => SamplerType.TextureCube, "cubearray" => SamplerType.TextureCube | SamplerType.Array,
_ => SamplerType.Texture2D,
};
}
public TextureFormat QueryTextureFormat(int handle, int cbufSlot = -1)
{
int slot = TexSlot(handle, cbufSlot);
string f = _job["img"] is JsonObject t && slot >= 0 && t[slot.ToString()] is JsonObject o ? (string)o["fmt"] : null;
if (f == null) { Notes.Add($"图像句柄 {handle:X} 槽 {slot} 无 PC 格式,按 R8G8B8A8Unorm"); return TextureFormat.R8G8B8A8Unorm; }
return Enum.TryParse(f, true, out TextureFormat tf) ? tf : TextureFormat.R8G8B8A8Unorm;
}
int Local(int i) => _job["local"] is JsonArray a && a.Count > i ? (int)a[i] : 1;
public int QueryComputeLocalSizeX() => Local(0);
public int QueryComputeLocalSizeY() => Local(1);
public int QueryComputeLocalSizeZ() => Local(2);
public int QueryComputeSharedMemorySize() => _job["shared"] is JsonNode n ? (int)n : 0; // 配对 PC 的 groupshared 声明之和 | sum of the paired PC shader's groupshared declarations
static AttributeType Attr(string s) => s switch { "sint" => AttributeType.Sint, "uint" => AttributeType.Uint, _ => AttributeType.Float };
public GpuGraphicsState QueryGraphicsState()
{
Array32<AttributeType> attr = default; Array8<AttributeType> fout = default;
if (_job["attr"] is JsonObject a) foreach (var kv in a) attr[int.Parse(kv.Key)] = Attr((string)kv.Value);
if (_job["fout"] is JsonObject f) foreach (var kv in f) fout[int.Parse(kv.Key)] = Attr((string)kv.Value);
return new GpuGraphicsState(false, InputTopology.Triangles, false, TessPatchType.Triangles, TessSpacing.EqualSpacing,
false, false, false, false /* 深度 0..1 | depth 0..1 */, false, 1f, AlphaTestOp.Always, 0f, attr, false, fout, false,
false /* 不做 Y 取反 | no Y flip */, true /* 原点左上 | origin upper-left */, false);
}
public bool QueryHostSupportsTextureShadowLod() => true;
// 作业 reduced = true:放宽精度——翻译器只给强制精确的运算打 NoContraction(缺省全部打:保持 Maxwell 分开舍入的逐位结果,代价是 MSL 里大量禁优化的 spvFMul 等)
// Job reduced = true: relaxed precision - the translator marks NoContraction only on operations that must be exact (the default marks all: keeps the bit-exact results of Maxwell's separate rounding, at the cost of many optimization-disabled spvFMul etc. in the MSL)
public bool QueryHostReducedPrecision() => _job["reduced"] is JsonNode n && (bool)n;
}
static int Main(string[] args)
{
if (args.Length == 1 && args[0] == "--source-sha") // 嵌入的 Program.cs + csproj 的 sha256 前 16 位(dmsh_chain.py 同口径) | first 16 digits of the sha256 of the embedded Program.cs + csproj (same convention as dmsh_chain.py)
{
var asm = typeof(SwshXlate).Assembly; var ms = new MemoryStream();
foreach (var n in new[] { "src0", "src1" }) asm.GetManifestResourceStream(n).CopyTo(ms);
Console.WriteLine(Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(ms.ToArray()))[..16].ToLowerInvariant());
return 0;
}
var jobs = JsonNode.Parse(File.ReadAllText(args[0])).AsArray(); string outDir = args[1]; Directory.CreateDirectory(outDir);
int ok = 0, bad = 0;
foreach (JsonObject job in jobs)
{
string key = (string)job["key"];
try
{
byte[] code = File.ReadAllBytes((string)job["code"]);
var acc = new Accessor(code, job);
// 作业 debug = false:关 DebugMode(DebugMode 会跳过 AST 优化器,产物满是临时变量;不改语义)
// Job debug = false: turn off DebugMode (DebugMode skips the AST optimizer and the output is full of temporaries; semantics unchanged)
var flags = (job["debug"] is JsonNode dbg && !(bool)dbg ? 0 : TranslationFlags.DebugMode) | ((string)job["stage"] == "cs" ? TranslationFlags.Compute : 0);
var ctx = Translator.CreateContext(0, acc, new TranslationOptions(TargetLanguage.Spirv, TargetApi.Vulkan, flags));
ShaderProgram p = ctx.Translate();
File.WriteAllBytes(Path.Combine(outDir, key + ".spv"), p.BinaryCode);
var res = new JsonObject
{
["key"] = key, ["stage"] = (string)job["stage"], ["notes"] = new JsonArray(acc.Notes.ConvertAll(n => (JsonNode)n).ToArray()),
["cbufs"] = new JsonArray(), ["sbufs"] = new JsonArray(), ["textures"] = new JsonArray(), ["images"] = new JsonArray(),
["uses_frag_coord"] = p.Info.UsesFragCoord, ["frag_out_map"] = p.Info.FragmentOutputMap,
};
foreach (var b in p.Info.CBuffers) res["cbufs"].AsArray().Add(new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot });
foreach (var b in p.Info.SBuffers) res["sbufs"].AsArray().Add(new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot, ["cb_slot"] = b.SbCbSlot, ["cb_offset"] = b.SbCbOffset, ["flags"] = (int)b.Flags });
foreach (var (list, name) in new[] { (p.Info.Textures, "textures"), (p.Info.Images, "images") })
foreach (var t in list) res[name].AsArray().Add(new JsonObject { ["binding"] = t.Binding, ["type"] = (int)t.Type, ["format"] = t.Format.ToString(), ["cbuf_slot"] = t.CbufSlot, ["handle"] = t.HandleIndex, ["array"] = t.ArrayLength, ["separate"] = t.Separate, ["flags"] = (int)t.Flags });
File.WriteAllText(Path.Combine(outDir, key + ".res.json"), res.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
ok++;
}
catch (Exception e) { bad++; Console.Error.WriteLine($"【红】{key}:{e.GetType().Name}:{e.Message.Split('\n')[0]}"); if (Environment.GetEnvironmentVariable("DMSH_STACK") != null) Console.Error.WriteLine(e.StackTrace); }
}
Console.WriteLine($"翻译 {ok} 成功,{bad} 失败");
return bad == 0 ? 0 : 1;
}
}
+19
View File
@@ -0,0 +1,19 @@
<!-- Switch 着色器 → SPIR-V 翻译工具。引用仓内收录的 Ryujinx 着色器翻译库源码(dm/third_party/ryujinx);可用 -p:RyuSrc=<目录> 指到别的一份。 -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>disable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RyuSrc Condition="'$(RyuSrc)' == ''">$(MSBuildThisFileDirectory)../../../third_party/ryujinx</RyuSrc>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(RyuSrc)/src/Ryujinx.Graphics.Shader/Ryujinx.Graphics.Shader.csproj" />
<ProjectReference Include="$(RyuSrc)/src/Ryujinx.Common/Ryujinx.Common.csproj" />
</ItemGroup>
<!-- 嵌入自身源码:参数 source-sha 报出,dmsh_chain.py 核对翻译器是用仓内源编的 -->
<ItemGroup>
<EmbeddedResource Include="Program.cs" LogicalName="src0" />
<EmbeddedResource Include="dmsh_xlate.csproj" LogicalName="src1" />
</ItemGroup>
</Project>
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
# 从 nvn.h 的 PFNNVN*PROC 原型生成宿主侧签名检查表 nvn_protos.h。
# 苹果 arm64 与 Switch 的 AAPCS64 差异:<32 位整型参数苹果要求调用方扩展、Switch 不扩展 ⇒
# NVNboolean 参数在宿主签名里一律换成 uint32_t(实现里只看低 8 位);其余 <32 位参数出现即报红。
# 栈传参(>8 个整型或 >8 个浮点参数)两边打包规则不同 ⇒ 出现即报红。
# 用法:gen_protos.py <nvn.h> <名字表(一行一个, 加载顺序)> <输出 .h>
# Generate the host-side signature check table nvn_protos.h from the PFNNVN*PROC prototypes in nvn.h.
# Difference between Apple arm64 and Switch AAPCS64: for integer arguments narrower than 32 bits, Apple requires the caller to extend them and Switch does not ⇒
# NVNboolean parameters are always replaced with uint32_t in the host signature (the implementation only looks at the low 8 bits); any other <32-bit parameter is reported as a failure on sight.
# Stack-passed arguments (>8 integer or >8 floating-point parameters) are packed differently on the two sides ⇒ reported a failure on sight.
# Usage: gen_protos.py <nvn.h> <name table (one per line, in load order)> <output .h>
import re, sys
hdr, names_path, out = sys.argv[1:4]
src = open(hdr).read()
protos = {}
for m in re.finditer(r'typedef\s+([\w\s\*]+?)\s*\(\*PFNNVN(\w+)PROC\)\s*\(([^;]*?)\);', src, re.S):
ret, key, args = m.group(1).strip(), m.group(2), ' '.join(m.group(3).split())
protos[key] = (ret, [a.strip() for a in args.split(',')] if args.strip() not in ('', 'void') else [])
FP = re.compile(r'^(const\s+)?(float|double)$')
SMALL = re.compile(r'^(const\s+)?(uint8_t|int8_t|uint16_t|int16_t|char|unsigned char|short|unsigned short|bool)$')
names = [l.strip() for l in open(names_path) if l.strip()]
lines = ['// 由 dm/gfx/tools/gen_protos.py 生成,勿手改。NVNboolean 参数已换成 uint32_t。', '#pragma once', '#include "nvn.h"', '']
red, missing = [], []
for n in names:
key = n[3:].upper()
if key not in protos:
missing.append(n)
continue
ret, args = protos[key]
gp = fp = 0
conv = []
for a in args:
t = re.sub(r'\s+\w+$', '', a) if not a.endswith('*') and len(a.split()) > 1 and a.split()[-1] not in ('int', 'float', 'double', 'char') and not a.split()[-1].endswith('_t') and not a.split()[-1].startswith(('NVN', 'PFN')) else a
t = t.strip()
if FP.match(t): fp += 1
else: gp += 1
if t == 'NVNboolean': t = 'uint32_t'
elif SMALL.match(t): red.append(f'{n}: <32 位参数 {t}')
conv.append(t)
if gp > 8 or fp > 8: red.append(f'{n}: 栈传参 gp={gp} fp={fp}')
lines.append(f'typedef {ret} (*NVNT_{n})({", ".join(conv) if conv else "void"});')
lines.append('')
lines.append('// 头文件里没有原型的名字(新版接口):只能接记名桩')
for n in missing: lines.append(f'// {n}')
open(out, 'w').write('\n'.join(lines) + '\n')
print(f'原型 {len(names) - len(missing)} / 名字 {len(names)};无原型 {len(missing)};报红 {len(red)}')
for r in red: print(' 红', r)
# 计数跳板:每个名字一个静态汇编入口 _nvnth_<i>,原子累加 nvn_slot[i].cnt 后跳到 nvn_slot[i].fn。
# 不在运行期生成代码(iOS 无 JIT),x16/x17 是过程间暂存寄存器,跳板可自由使用。
# 跳进目标时 x16 仍指向本槽:未实现桩 nvn_unimpl_entry 据此反查名字。
# Counting trampolines: one static assembly entry _nvnth_<i> per name, which atomically increments nvn_slot[i].cnt and then jumps to nvn_slot[i].fn.
# No code is generated at runtime (iOS has no JIT); x16/x17 are intra-procedure-call scratch registers, so the trampoline may use them freely.
# On entry to the target, x16 still points to this slot: the unimplemented stub nvn_unimpl_entry uses it to look the name back up.
th = out.replace('nvn_protos.h', 'nvn_thunks.S')
S = ['// 由 dm/gfx/tools/gen_protos.py 生成,勿手改。',
'// 计数用 LSE 原子 stadd(ARMv8.1;Apple A12 / M1 起全部支持):下一行让本文件不依赖编译器的 -mcpu 基线。',
' .arch_extension lse', ' .text', ' .p2align 2']
for i, n in enumerate(names):
S += [f' .globl _nvnth_{i}', f'_nvnth_{i}:',
' adrp x16, _nvn_slot@PAGE', ' add x16, x16, _nvn_slot@PAGEOFF',
f' mov x17, #{i * 16}', ' add x16, x16, x17',
' mov x17, #1', ' stadd x17, [x16]', ' ldr x17, [x16, #8]', ' br x17']
S += [' .data', ' .p2align 3', ' .globl _nvn_thunk', '_nvn_thunk:'] + [f' .quad _nvnth_{i}' for i in range(len(names))]
S += [' .globl _nvn_names', '_nvn_names:'] + [f' .quad Ln{i}' for i in range(len(names))]
S += [' .cstring'] + [f'Ln{i}: .asciz "{n}"' for i, n in enumerate(names)]
open(th, 'w').write('\n'.join(S) + '\n')
hn = out.replace('nvn_protos.h', 'nvn_count.h')
open(hn, 'w').write('// 由 gen_protos.py 生成\n#pragma once\n#define NVN_NFUNC %d\n' % len(names))
+70
View File
@@ -0,0 +1,70 @@
# Maxwell(Tegra X1)着色器机器码里的资源引用:只解读绑定映射需要的那几类,不是完整反汇编器。
# 指令位模式取自 yuzu shader decode 表;代码段布局:图形阶段 = 0x30 NVN 头(0x12345678)+ 0x50 SPH + 指令,
# 计算阶段直接是指令;每 4 个 64 位字的第 1 个是调度控制字。
# 全量实测(10847 条变体,tools/shader_map.py)得出 NVN 绑定 ↔ D3D 寄存器:
# uniform 缓冲 binding r ↔ cb_r,机器码里是 c[3 + r](每阶段 14 个,c[3]..c[16];更高的 c[22]/c[27] 是驱动内部)
# 分离贴图 slot r ↔ t_r,句柄在 c[2][0x168 + 8r](读法两种:c[2] 操作数,或贴图指令立即数贴图号 ×4)
# 分离采样器 slot r ↔ s_r,句柄在 c[2][0x568 + 8r](例外 1 条:cs_terrain_composite 多用 s2,PC 无)
# 存储缓冲 slot r ↔ u_r 或只读结构化/原始缓冲 t_r(同一编号空间),地址/大小在 c[0][基址 + 0x10 r]
# 基址:顶点 0x110、计算 0x310、像素 0x510;10847 条双向全等
# Resource references in Maxwell (Tegra X1) shader machine code: only decodes the few kinds needed for the binding mapping; not a full disassembler.
# Instruction bit patterns are taken from the yuzu shader decode table; code segment layout: graphics stage = 0x30 NVN header (0x12345678) + 0x50 SPH + instructions,
# compute stage is instructions directly; the 1st of every 4 64-bit words is the scheduling control word.
# A full measurement (10847 variants, tools/shader_map.py) gives NVN binding ↔ D3D register:
# uniform buffer binding r ↔ cb_r, which is c[3 + r] in machine code (14 per stage, c[3]..c[16]; the higher c[22]/c[27] are driver-internal)
# separate texture slot r ↔ t_r, handle at c[2][0x168 + 8r] (two ways to read it: a c[2] operand, or the texture instruction's immediate texture index ×4)
# separate sampler slot r ↔ s_r, handle at c[2][0x568 + 8r] (1 exception: cs_terrain_composite additionally uses s2, absent on PC)
# storage buffer slot r ↔ u_r or read-only structured/raw buffer t_r (same numbering space), address/size at c[0][base + 0x10 r]
# base: vertex 0x110, compute 0x310, pixel 0x510; all 10847 match exactly in both directions
import struct
TEX_BASE, SAMP_BASE, UBO_FIRST, UBO_LAST = 0x168, 0x568, 3, 16
SSBO_BASE = {'vs': 0x110, 'cs': 0x310, 'ps': 0x510}
def instrs(code, graphics):
off = 0x80 if graphics and code[:4] == bytes.fromhex('78563412') else 0
out = []
for k in range(off, len(code) - 7, 8):
if ((k - off) // 8) % 4 == 0: continue
out.append(struct.unpack_from('<Q', code, k)[0])
return out
def match(w, pat):
for i, ch in enumerate(pat):
if ch != '-' and int(ch) != (w >> (63 - i)) & 1: return False
return True
def cbuf_alu(ins):
"""操作数类为常量缓冲的 ALU 指令(最高 4 位 = 0100):{(索引, 字节偏移)} | ALU instructions whose operand class is constant buffer (top 4 bits = 0100): {(index, byte offset)}"""
return {((w >> 34) & 0x1f, ((w >> 20) & 0x3fff) * 4) for w in ins if (w >> 60) == 0x4 and w}
def ldc(ins):
"""LDC(按下标读常量缓冲):{(索引, 字节偏移)} | LDC (read constant buffer by index): {(index, byte offset)}"""
return {((w >> 36) & 0x1f, (w >> 20) & 0xffff) for w in ins if match(w, '1110111110010---')}
def bindings(code, stage):
ins = instrs(code, stage != 'cs')
refs = cbuf_alu(ins) | ldc(ins)
ubo = {i - UBO_FIRST for i, _ in refs if UBO_FIRST <= i <= UBO_LAST}
c2 = {o for i, o in refs if i == 2}
# 立即数贴图号(TEX/TEXS/TLD/TLDS/TLD4/TLD4S 的 bits 36..48)= 句柄在 c[2] 里的字偏移,×4 即字节偏移(内嵌着色器 TLDS 0x6e→t10 核实)
# Immediate texture index (bits 36..48 of TEX/TEXS/TLD/TLDS/TLD4/TLD4S) = word offset of the handle within c[2]; ×4 gives the byte offset (verified with the embedded shader's TLDS 0x6e→t10)
for w in ins:
for pat in ('110000----111---', '110010----111---', '11011100--11----', '1101111100------', '1101-00---------', '1101-01---------'):
if match(w, pat): c2.add(((w >> 36) & 0x1fff) * 4); break
tex = {(o - TEX_BASE) // 8 for o in c2 if TEX_BASE <= o < SAMP_BASE and (o - TEX_BASE) % 8 == 0}
samp = {(o - SAMP_BASE) // 8 for o in c2 if o >= SAMP_BASE and (o - SAMP_BASE) % 8 == 0}
base = SSBO_BASE.get(stage)
ssbo = {(o - base) // 16 for i, o in refs if i == 0 and base and o >= base and (o - base) % 16 == 0 and (o - base) // 16 < 16} if base else set()
drv = sorted(o for o in c2 if o < TEX_BASE)
return {'ubo': ubo, 'tex': tex, 'samp': samp, 'ssbo': ssbo, 'c2drv': drv}
def vs_inputs(code):
"""顶点着色器读取的通用属性槽:ALD(1110111111011---)的属性地址 bits 20..29,通用属性 n 在 0x80 + 16n | Generic attribute slots read by the vertex shader: attribute address bits 20..29 of ALD (1110111111011---); generic attribute n is at 0x80 + 16n"""
ins = instrs(code, True)
return {((w >> 20) & 0x3ff) - 0x80 >> 4 for w in ins if match(w, '1110111111011---') and 0x80 <= ((w >> 20) & 0x3ff) < 0x280}
def sph_stage(code):
"""图形着色器 SPH 头的阶段字段(第 0 字 bits 10..13):1 顶点、5 像素 | Stage field of the graphics shader SPH header (word 0, bits 10..13): 1 vertex, 5 pixel"""
if code[:4] != bytes.fromhex('78563412'): return None
return {1: 'vs', 5: 'ps'}.get((struct.unpack_from('<I', code, 0x30)[0] >> 10) & 0xf)
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
# 在没有苹果 Metal 编译器的机器上跑着色器出库链(Windows / Linux / 没装 Xcode 的 Mac;给 tools/d2rm_pack.py 用)。
# 用法:nometal_run.py <脚本.py> [参数…] 例:nometal_run.py dmsh_build.py <包目录> <缓存目录>
# 做法:不改出库链的任何一个文件(它们的内容参与翻译链版本,一改内测的着色器库就得整体换代),只在本进程里把它们调外部命令的
# 那一个入口(subprocess.run)接过来,认出下面几条命令自己答,其余原样放行:
# xcrun -sdk <x> metal --version → 答「none」(工具指纹里编译器记成不用 → 链版本自成一支,缓存与正常模式互不相混)
# xcrun -sdk <x> metal -c <源码> -o <中间件> → 把源码拷成中间件(换行统一成 \n)
# xcrun -sdk <x> metallib <中间件> -o <库> → 把中间件原样拷成库
# which <名字> → 用 Python 自己找
# cp -c <甲> <乙> → 普通拷贝
# 结果:「库文件」(*_b.metallib / *_bf.metallib)里放的是着色器源码。壳(DM_SHELL 构建)的图形层发现库不是编好的就在设备上现编
# (gfx/nvn/nvn_mtl.m),系统会把编好的结果缓存,第二次启动起不再编。
# 少掉的一道:正常模式下苹果编译器顺带验了每份源码能编过;这里不验,编不过的要到设备上用到它时才报红。
# Runs the shader build chain on a machine without Apple's Metal compiler (Windows / Linux / a Mac without Xcode; for use by tools/d2rm_pack.py).
# Usage: nometal_run.py <script.py> [args...] Example: nometal_run.py dmsh_build.py <package dir> <cache dir>
# How: not a single file of the build chain is modified (their contents feed into the translation chain version, and any change would force a whole new generation of the beta shader libraries); only, within this process, the one entry through which they call external commands
# (subprocess.run) is taken over: the commands below are recognized and answered here, and everything else is passed through unchanged:
# xcrun -sdk <x> metal --version → answers "none" (the compiler is recorded as unused in the tool fingerprint → the chain version forms its own branch, and its cache never mixes with normal mode's)
# xcrun -sdk <x> metal -c <source> -o <intermediate file> → copies the source as the intermediate file (line endings normalized to LF)
# xcrun -sdk <x> metallib <intermediate file> -o <library> → copies the intermediate file verbatim as the library
# which <name> → looked up by Python itself
# cp -c <a> <b> → ordinary copy
# Result: the "library files" (*_b.metallib / *_bf.metallib) contain shader source. When the graphics layer of the shell (DM_SHELL build) finds that a library is not a compiled one, it compiles it on the device
# (gfx/nvn/nvn_mtl.m); the system caches the compiled result, and from the second launch on nothing is compiled again.
# The one check that is lost: in normal mode Apple's compiler also verifies along the way that every source compiles; here that is not verified, and one that fails to compile only reports a failure when it is used on the device.
import os, runpy, shutil, subprocess, sys
_real = subprocess.run
def _done(args, out=''):
return subprocess.CompletedProcess(args, 0, stdout=out, stderr='')
def run(args, *a, **k):
text = k.get('text') or k.get('universal_newlines')
enc = (lambda s: s) if text else (lambda s: s.encode())
if isinstance(args, (list, tuple)) and args:
c = [str(x) for x in args]
if c[0] == 'xcrun' and 'metal' in c and '--version' in c: return _done(args, enc('none\n'))
if c[0] == 'xcrun' and 'metal' in c and '-c' in c and '-o' in c: # 源码 = metal 之后第一个不是选项、也不是 -o 的值的参数(iOS 那条命令在 -c 后面还带一个版本选项) | source = the first argument after metal that is neither an option nor the value of -o (the iOS command also carries a version option after -c)
o = c.index('-o'); src = [x for i, x in enumerate(c[c.index('metal') + 1:], c.index('metal') + 1) if not x.startswith('-') and i != o + 1]
if len(src) != 1: raise RuntimeError('nometal_run:认不出源码参数 %r' % c)
with open(src[0], 'rb') as f: b = f.read()
with open(c[o + 1], 'wb') as f: f.write(b.replace(b'\r\n', b'\n')) # Windows 上 spirv-cross 写出的源码是 \r\n 换行:进安装包前归一,同样的输入各系统出的包才相同 | On Windows spirv-cross writes sources with CRLF line endings: normalize before they go into the install package, so the same input gives the same package on every system
return _done(args, enc(''))
if c[0] == 'xcrun' and 'metallib' in c and '-o' in c: shutil.copyfile(c[c.index('metallib') + 1], c[c.index('-o') + 1]); return _done(args, enc(''))
if c[0] == 'xcrun': raise RuntimeError('nometal_run:没认出的 xcrun 命令 %r' % c)
if c[0] == 'which' and len(c) == 2: return _done(args, enc((shutil.which(c[1]) or '') + '\n'))
if c[0] == 'cp' and len(c) == 4 and c[1] == '-c': shutil.copyfile(c[2], c[3]); return _done(args, enc(''))
return _real(args, *a, **k)
if __name__ == '__main__':
if len(sys.argv) < 2: sys.exit(__doc__ or '用法:nometal_run.py <脚本.py> [参数…]')
subprocess.run = run
script = os.path.abspath(sys.argv[1]); sys.argv = sys.argv[1:]; sys.path.insert(0, os.path.dirname(script))
runpy.run_path(script, run_name='__main__')
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
# main 的 NVN 取址表与静态调用面(3.3.94012)。
# 1) 解析 main 里的 NVN 加载函数(按名字取址后逐个存进全局指针槽)→ 名字 → 槽;
# 2) 全 .text 扫「ldr xT,[xN,#imm]」读槽:从读取点往回找 xN 的上一次写入,是 adrp 到槽页才算一次调用点。
# (前向寄存器跟踪会把陈旧值当槽地址、或漏掉循环外提的 adrp,两种都抽查出过错,故用回溯。)
# 用法:nvn_slots.py <main 原映像 .bin(dm/tools/nso.py 解出)> <输出 tsv> [名字表输出]
# 输出列:名字 槽地址 调用点数 首个调用点;名字表按槽地址(= 加载顺序)。
# main's NVN address-lookup table and static call surface (3.3.94012).
# 1) Parse the NVN loader function in main (looks up addresses by name and stores them one by one into global pointer slots) → name → slot;
# 2) Scan all of .text for "ldr xT,[xN,#imm]" slot reads: search backward from the read for the previous write to xN; it only counts as a call site if that write is an adrp to the slot's page.
# (Forward register tracking treats stale values as slot addresses, or misses an adrp hoisted out of a loop; spot checks found both kinds of error, hence the backward trace.)
# Usage: nvn_slots.py <main raw image .bin (extracted by dm/tools/nso.py)> <output tsv> [name table output]
# Output columns: name, slot address, call site count, first call site; the name table is ordered by slot address (= load order).
import struct, sys
LOADER = 0x1739290 # main 内 NVN 加载函数(3.3.94012;换版本先重新定位) | NVN loader function inside main (3.3.94012; re-locate it first when changing versions)
img, out = sys.argv[1], sys.argv[2]
d = open(img, 'rb').read()
TEXT_END = 0x1b786a0 # main .text 尾(NSO 段头) | end of main .text (NSO segment header)
N = TEXT_END // 4
w = struct.unpack_from('<%dI' % N, d, 0)
def adrp(x, pc):
imm = ((x >> 29) & 3) | (((x >> 5) & 0x7ffff) << 2)
if imm & (1 << 20): imm -= 1 << 21
return (pc & ~0xfff) + (imm << 12)
def cstr(a): return d[a:d.index(b'\0', a)].decode()
# 1) 加载函数:adrp/add x1 = 名字,str x0,[xn,#imm] = 槽
# 1) Loader function: adrp/add x1 = name, str x0,[xn,#imm] = slot
i, reg, cur, slot = LOADER // 4, {}, None, {}
while w[i] != 0xd65f03c0:
x, pc = w[i], i * 4
if x & 0x9f000000 == 0x90000000: reg[x & 31] = adrp(x, pc)
elif x & 0xffc00000 == 0x91000000 and (x & 31) == 1: cur = cstr(reg[(x >> 5) & 31] + ((x >> 10) & 0xfff))
elif x & 0xffc00000 == 0xf9000000 and (x & 31) == 0: slot[reg[(x >> 5) & 31] + ((x >> 10) & 0xfff) * 8] = cur
i += 1
offs = {a & 0xfff for a in slot}
def writes(x, r):
"""x 是否写通用寄存器 r(近似、偏保守) | Whether x writes general-purpose register r (approximate, conservative)"""
op0 = (x >> 25) & 0xf
if x & 0xfc000000 == 0x94000000 or x & 0xfffffc1f == 0xd63f0000: return r <= 18 # bl / blr
if op0 in (0b1000, 0b1001, 0b0101, 0b1101): return (x & 31) == r # 数据处理 | data processing
if op0 & 0b0101 == 0b0100: # 读写内存 | memory load/store
L = (x >> 22) & 1
if (x >> 27) & 7 == 0b101:
wb = (x >> 23) & 3 in (1, 3)
return (L and ((x & 31) == r or ((x >> 10) & 31) == r)) or (wb and ((x >> 5) & 31) == r)
if (x >> 27) & 7 == 0b111 and (x >> 24) & 3 == 0:
wb = (x >> 21) & 1 == 0 and (x >> 10) & 3 in (1, 3)
return (L and (x & 31) == r) or (wb and ((x >> 5) & 31) == r)
if (x >> 27) & 7 == 0b111: return bool(L) and (x & 31) == r
if (x >> 27) & 7 == 0b011: return (x & 31) == r
return False
# 2) 回溯归属每次读槽
# 2) Attribute each slot read by tracing backward
uses = {a: [] for a in slot}
for i in range(N):
x = w[i]
if x & 0xffc00000 != 0xf9400000: continue
off = ((x >> 10) & 0xfff) * 8
rn = (x >> 5) & 31
if off not in offs or rn == 31: continue
for j in range(i - 1, max(i - 4000, -1), -1):
y = w[j]
if y == 0xd65f03c0: break
if writes(y, rn):
if y & 0x9f000000 == 0x90000000 and (y & 31) == rn and adrp(y, j * 4) + off in uses:
uses[adrp(y, j * 4) + off].append(i * 4)
break
with open(out, 'w') as f:
f.write('# kind: evidence main NVN 取址槽与静态调用点(nvn_slots.py)\nname\tslot\tnuses\tfirst_use\n')
for a in sorted(slot):
u = uses[a]; f.write('%s\t%x\t%d\t%s\n' % (slot[a], a, len(u), '%x' % u[0] if u else '-'))
if len(sys.argv) > 3: open(sys.argv[3], 'w').write(''.join(slot[a] + '\n' for a in sorted(slot)))
used = sum(1 for a in slot if uses[a])
print('槽 %d,有调用点 %d,调用点 %d' % (len(slot), used, sum(len(v) for v in uses.values())))
+23
View File
@@ -0,0 +1,23 @@
# 逐通道 GPU:按帧内序号平均时间线增量 inc_ms;与 @gpu_ms 对照(列见 nvn_mtl.m DM_NVN_PASSGPU 注释)
# Per-pass GPU: average the timeline increment inc_ms by in-frame index; compare against @gpu_ms (for the columns see the DM_NVN_PASSGPU comment in nvn_mtl.m)
import sys, collections, statistics as S
X=sys.argv[1]; F0=int(sys.argv[2]) if len(sys.argv)>2 else 300; N=int(sys.argv[3]) if len(sys.argv)>3 else 10
rows=[l.rstrip('\n').split('\t') for l in open(f'{X}/passgpu.tsv')][1:]
inc=collections.defaultdict(list); per=collections.defaultdict(float); meta={}
for r in rows:
f=int(r[0])
if f<=F0: continue
inc[int(r[1])].append(float(r[4])); per[f]+=float(r[4]); meta[int(r[1])]=r
g={}
try:
for l in open(f'{X}/frames.tsv'):
p=l.rstrip('\n').split('\t')
if len(p)==3 and p[0].isdigit() and p[1]=='@gpu_ms': g[int(p[0])]=float(p[2])
except FileNotFoundError: pass
c=[f for f in per if f in g]
print('帧数 %d;每帧增量之和 p50 %.2f / p95 %.2f ms%s'%(len(per),S.median(per.values()),sorted(per.values())[int(len(per)*.95)],';同帧 @gpu_ms p50 %.2f ms'%S.median(g[f] for f in c) if c else ''))
tot=sum(S.mean(v) for v in inc.values())
print('前列(帧内序号:增量均值 ms,占比 | 尺寸 颜色格式 深度格式 读入 绘制数 种类)')
for k in sorted(inc,key=lambda k:-S.mean(inc[k]))[:N]:
r=meta[k]; m=S.mean(inc[k]); print(' #%d:%.3f ms %4.1f%% | %sx%s fmt%s d%s %s %s 绘制 %s'%(k,m,100*m/tot,r[5],r[6],r[7],r[8],r[9],r[10],r[2]))
print('通道数 / 帧:%d;合计 %.2f ms'%(len(inc),tot))
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
# Switch 着色器 → PC 着色器(DXBC)→ PC 链 MSL(metallib)映射表。
# 依据:两侧 data/hd/shaders 都是 162 个同名 SHAD 包,每个变体一条 BTCD 记录,记录数逐包相等(共 10847 条);
# 记录头除尺寸外只差平台号(PC 3 / Switch 5),没有排列键 ⇒ 按包内序号一一对应。
# 顺序对齐的证据:计算着色器线程组大小逐条 22/22 相等;记录数 ≥16 的 22 个包代码量秩相关,对齐 0.81–1.00、错位一条全部更低。
# Switch 记录:头之后 = GPU 代码段(0x12345678 开头),其后 = 控制段(0x98761234 开头,长度见记录头)。
# 运行期 nvnProgramSetShaders 拿到的是控制段指针 ⇒ 键 = sha256(控制段)[:16]。
# PC 记录:内含一个 DXBC;PC 链缓存文件名 = sha256(DXBC)[:16].metallib(platform/shell/mtl12/shaders/build_cache.py)。
# 绑定映射(maxwell_refs.py 头注释):NVN 槽号 = D3D 寄存器号,按 Switch 机器码实际引用逐条核「Switch 用到的 ⊆ PC 声明的」。
# 键冲突(Switch 二进制相同、PC DXBC 不同)时选一份:与 Switch 实际用到的输出数 / cb / t / s 差异最小者;
# 并列取最简(输出少、资源少),再并列取 DXBC 哈希最小(确定性)。选择与理由写进 <输出>.conflicts.tsv。
# 程序本体内嵌的着色器(不在包里):Switch main 原映像里有 10 个控制段,前 6 个是图形着色器,与 PC D2R.exe 内嵌的 6 个 DXBC 同序一一对应
# (两边同位置各有一对完全相同的重复项);后 4 个是计算着色器,PC 无对应,另行处理。
# 用法:shader_map.py <PC 包目录> <Switch 包目录> <PC metallib 缓存目录> <输出 tsv> [<main 原映像> <PC D2R.exe>]
# Mapping table: Switch shader → PC shader (DXBC) → PC-chain MSL (metallib).
# Basis: data/hd/shaders on both sides holds 162 SHAD packages with the same names, one BTCD record per variant, and record counts are equal package by package (10847 in total);
# apart from sizes, record headers differ only in the platform number (PC 3 / Switch 5), and there is no permutation key ⇒ map one-to-one by index within the package.
# Evidence of order alignment: compute shader thread group sizes are equal record by record, 22/22; for the 22 packages with ≥16 records, code size is rank-correlated, 0.81–1.00 when aligned and lower in every case when shifted by one record.
# Switch record: after the header = GPU code segment (starts with 0x12345678), followed by = control segment (starts with 0x98761234, length in the record header).
# At runtime nvnProgramSetShaders receives the control segment pointer ⇒ key = sha256(control segment)[:16].
# PC record: contains one DXBC; PC-chain cache file name = sha256(DXBC)[:16].metallib (platform/shell/mtl12/shaders/build_cache.py).
# Binding mapping (header comment of maxwell_refs.py): NVN slot number = D3D register number; verified record by record against what the Switch machine code actually references that "used by Switch ⊆ declared by PC".
# On a key conflict (same Switch binary, different PC DXBC) pick one: the one with the smallest difference from the output count / cb / t / s actually used by Switch;
# on a tie take the simplest (fewer outputs, fewer resources), on a further tie take the smallest DXBC hash (deterministic). The choice and the reason are written to <output>.conflicts.tsv.
# Shaders embedded in the executable itself (not in packages): the Switch main raw image has 10 control segments; the first 6 are graphics shaders and map one-to-one, in the same order, to the 6 DXBC embedded in PC D2R.exe
# (each side has a pair of identical duplicates at the same position); the last 4 are compute shaders with no PC counterpart, handled separately.
# Usage: shader_map.py <PC package dir> <Switch package dir> <PC metallib cache dir> <output tsv> [<main raw image> <PC D2R.exe>]
import hashlib, json, os, re, struct, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from maxwell_refs import bindings, vs_inputs, sph_stage
pc_dir, dm_dir, cache_dir, out = sys.argv[1:5]
def records(d):
r = [m.start() for m in re.finditer(b'BTCDBTCD', d)]
return [d[x:(r[k + 1] if k + 1 < len(r) else len(d))] for k, x in enumerate(r)]
def pc_dxbc(rec):
i = rec.find(b'DXBC')
return rec[i:i + struct.unpack_from('<I', rec, i + 24)[0]]
def dx_outputs(dx):
j = dx.find(b'OSGN')
if j < 0: return -1
n = struct.unpack_from('<I', dx, j + 8)[0]
return sum(1 for q in range(n) if struct.unpack_from('<I', dx, j + 16 + q * 24 + 8)[0] == 0)
def dm_parts(rec):
i = rec.find(bytes.fromhex('34127698')) # 控制段魔数(小端 0x98761234) | control segment magic (little-endian 0x98761234)
csz = struct.unpack_from('<I', rec, 0x28)[0] # 记录头:平台号 5、控制段长度… | record header: platform number 5, control segment length...
return rec[i:i + csz], i
STAGE = {'vs': '顶点', 'ps': '像素', 'cs': '计算', 'hs': '外壳', 'ds': '域'}
cache = set(os.listdir(cache_dir))
rows, keys, cand, dxs, locs = [], {}, {}, {}, {}
for name in sorted(os.listdir(dm_dir)):
A = records(open(os.path.join(pc_dir, name), 'rb').read())
B = records(open(os.path.join(dm_dir, name), 'rb').read())
if len(A) != len(B): sys.exit(f'【红】{name} 记录数不等 PC {len(A)} / Switch {len(B)}')
for k, (a, b) in enumerate(zip(A, B)):
dx = pc_dxbc(a); ctl, _ = dm_parts(b)
if len(ctl) < 0x100: sys.exit(f'【红】{name}#{k} 控制段异常')
swk = hashlib.sha256(ctl).hexdigest()[:16]; pck = hashlib.sha256(dx).hexdigest()[:16]
ml = pck + '.metallib' in cache
dm_out = struct.unpack_from('<I', ctl, 0x734)[0] if name.startswith('ps_') else -1
pc_out = dx_outputs(dx) if name.startswith('ps_') else -1
refl = json.load(open(os.path.join(cache_dir, pck + '.json')))['bindings'] if ml else []
pcb = {x['reg'] for x in refl if x['type'] == 'cbuffer'}
pt = {x['reg'] for x in refl if x['type'].startswith('texture') or x['type'].startswith('buffer')}
ps_ = {x['reg'] for x in refl if x['type'] == 'sampler'}
_, ci = dm_parts(b); sb = bindings(b[0x38:ci], name[:2])
pbuf = {x['reg'] for x in refl if x['type'] in ('buffer_raw', 'buffer_structured', 'atomic_alias')}
ok = int(sb['ubo'] <= pcb) | int(sb['tex'] <= pt) << 1 | int(sb['samp'] <= ps_) << 2 | int(sb['ssbo'] == pbuf) << 3
fmt = lambda x: ','.join(map(str, sorted(x))) or '-'
rows.append((name, k, STAGE.get(name[:2], name[:2]), swk, pck, int(ml), pc_out, dm_out,
fmt(sb['ubo']), fmt(sb['tex']), fmt(sb['samp']), fmt(sb['ssbo']), ok))
keys.setdefault(swk, set()).add(pck)
cand.setdefault(swk, {})[pck] = (pc_out, dm_out, pcb, pt, ps_, sb)
dxs[pck] = dx; locs.setdefault(swk, []).append(f'{name}#{k}')
if len(sys.argv) > 6:
mi = open(sys.argv[5], 'rb').read(); pe = open(sys.argv[6], 'rb').read()
dm_ctl = [m.start() for m in re.finditer(bytes.fromhex('34127698'), mi)]
pc_dx = []
for m in re.finditer(b'DXBC', pe):
o = m.start(); sz = struct.unpack_from('<I', pe, o + 24)[0] if o + 32 <= len(pe) else 0
if 64 < sz < 1 << 20 and o + sz <= len(pe) and struct.unpack_from('<I', pe, o + 20)[0] == 1: pc_dx.append(pe[o:o + sz])
gfx = [o for o in dm_ctl if mi.rfind(bytes.fromhex('78563412'), o - 0x1000, o) > 0]
# 按特征配对(不靠顺序:反汇编发现两边内嵌顺序不同):阶段取 SPH;集合差异 = cb/t/s 与(顶点)输入槽的对称差,取唯一最小
# Pair by features (not by order: disassembly showed the embedded order differs between the two sides): stage is taken from SPH; set difference = symmetric difference of cb/t/s and (vertex) input slots, take the unique minimum
def pc_feat(dx):
h = hashlib.sha256(dx).hexdigest()[:16]
j = json.load(open(os.path.join(cache_dir, h + '.json')))
bs = j['bindings']
return h, j['stage'], ({x['reg'] for x in bs if x['type'] == 'cbuffer'}, {x['reg'] for x in bs if x['type'].startswith('texture')},
{x['reg'] for x in bs if x['type'] == 'sampler'}, {x['location'] for x in j['vertex_inputs']})
pcs = [pc_feat(dx) for dx in pc_dx]
for k, o in enumerate(gfx):
g = mi.rfind(bytes.fromhex('78563412'), o - 0x1000, o)
code = mi[g:o]; stg = sph_stage(code); sb = bindings(code, stg)
dm = (sb['ubo'], sb['tex'], sb['samp'], vs_inputs(code) if stg == 'vs' else set())
cands = sorted((sum(len(a ^ b) for a, b in zip(dm, f)), h) for h, st, f in pcs if st == stg)
if not cands or (len(cands) > 1 and cands[0][0] == cands[1][0] and cands[0][1] != cands[1][1]):
sys.exit(f'【红】内嵌着色器 @{o:#x}({stg})配不出唯一的 PC 对应:{cands}')
pck = cands[0][1]; swk = hashlib.sha256(mi[o:o + 0x880]).hexdigest()[:16]
ml = pck + '.metallib' in cache
refl = json.load(open(os.path.join(cache_dir, pck + '.json')))['bindings'] if ml else []
pbuf = {x['reg'] for x in refl if x['type'] in ('buffer_raw', 'buffer_structured', 'atomic_alias')}
f = pcs[[h for h, _, _ in pcs].index(pck)][2]
ok = int(dm[0] <= f[0]) | int(dm[1] <= f[1]) << 1 | int(dm[2] <= f[2]) << 2 | int(sb['ssbo'] == pbuf) << 3
fmt = lambda x: ','.join(map(str, sorted(x))) or '-'
rows.append(('main.rodata@%x' % o, k, STAGE.get(stg, stg), swk, pck, int(ml), -1, -1, fmt(sb['ubo']), fmt(sb['tex']), fmt(sb['samp']), fmt(sb['ssbo']), ok))
keys.setdefault(swk, set()).add(pck)
print(f' 内嵌 @{o:#x} {stg} 用 cb{fmt(dm[0])} t{fmt(dm[1])} s{fmt(dm[2])} 输入{fmt(dm[3])} → PC {pck}(差异 {cands[0][0]},次优 {cands[1][0] if len(cands) > 1 else "-"})')
print(f'内嵌图形着色器 {len(gfx)} 个(metallib {sum(1 for r in rows[-len(gfx):] if r[5])} 个),内嵌计算着色器 {len(dm_ctl) - len(gfx)} 个未映射')
amb = {k: v for k, v in keys.items() if len(v) > 1}
with open(out, 'w') as f:
f.write('# kind: evidence Switch 着色器变体 → PC DXBC → PC 链 metallib(dm/gfx/tools/shader_map.py)\n')
f.write('# 键冲突(同一 Switch 控制段对应多份 PC DXBC):%d\n' % len(amb))
f.write('package\tindex\tstage\tdm_ctl_sha16\tpc_dxbc_sha16\tmetallib\tpc_outputs\tdm_outputs\tdm_ubo\tdm_tex\tdm_samp\tdm_ssbo\tsubset_ok(cb|t<<1|s<<2|ssbo全等<<3)\n')
for r in rows: f.write('\t'.join(map(str, r)) + '\n')
# 键冲突裁定
# Key conflict resolution
def dx_chunks(d):
out = {}
for i in range(struct.unpack_from('<I', d, 28)[0]):
o = struct.unpack_from('<I', d, 32 + 4 * i)[0]
out[d[o:o + 4]] = d[o + 8:o + 8 + struct.unpack_from('<I', d, o + 4)[0]]
return out
def klass(pcs):
ch = [dx_chunks(dxs[p]) for p in pcs]
code = [c.get(b'SHEX', c.get(b'SHDR')) for c in ch]
if len(set(code)) == 1: return '指令块相同·仅输入签名不同(建管线时按顶点着色器输出配对选)'
if len({len(x) for x in code}) == 1: return '指令块等长·输入签名不同(疑为输入寄存器重编号,同按配对选)'
return '指令块不同(真实代码差异,Switch 编成同一二进制;需运行期定位包与序号或画面确认)'
def score(c):
po, so, pcb, pt, ps_, sb = c
diff = (po != so and po >= 0) + len(pcb ^ sb['ubo']) + len(pt ^ sb['tex']) + len(ps_ ^ sb['samp'])
return (diff, max(po, 0) + len(pcb) + len(pt) + len(ps_))
with open(out + '.conflicts.tsv', 'w') as f:
f.write('# kind: evidence Switch 控制段键冲突的 PC 候选裁定(差异最小 → 最简 → 哈希最小)\n')
f.write('dm_ctl_sha16\tchosen_pc\tclass\tcandidates(pc:差异:规模)\trecords\n')
for k in sorted(amb):
cs = sorted(cand[k].items(), key=lambda kv: (score(kv[1]), kv[0]))
f.write('%s\t%s\t%s\t%s\t%s\n' % (k, cs[0][0], klass([p for p, _ in cs]), ' '.join('%s:%d:%d' % (p, *score(c)) for p, c in cs), ' '.join(locs[k])))
n = len(rows); ml = sum(r[5] for r in rows)
okc = [sum(1 for r in rows if r[12] >> b & 1) for b in range(4)]
print(f'绑定子集成立:cb {okc[0]}/{len(rows)},t {okc[1]}/{len(rows)},s {okc[2]}/{len(rows)};存储缓冲全等 {okc[3]}/{len(rows)}')
uniq_dm = len(keys); uniq_pc = len({r[4] for r in rows}); uniq_pc_ml = len({r[4] for r in rows if r[5]})
outd = [r for r in rows if r[6] >= 0 and r[6] != r[7]]
print(f'记录 {n};Switch 控制段去重 {uniq_dm};PC DXBC 去重 {uniq_pc};键冲突 {len(amb)}')
print(f'有 PC metallib 的记录 {ml}/{n};PC DXBC 去重后有 metallib {uniq_pc_ml}/{uniq_pc}')
print(f'像素着色器输出数不同(PC 多目标、Switch 少写){len(outd)} 条')
by = {}
for r in rows: by.setdefault(r[2], [0, 0]); by[r[2]][0] += 1; by[r[2]][1] += r[5]
for s, (t, m) in by.items(): print(f' {s}:记录 {t},有 metallib {m}')
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
# 每帧附件带宽预算表(目标 120 帧、≤ 20 GB/s → 每帧 ≤ 170 MB):从 DM_NVN_PASSDUMP 的一帧数据流按通道列读入 / 写回 MB,
# 按两者之和从大到小排。读入按 P 行 load 计(clear / dontcare 不计);写回按 P 行的附件计、扣掉 Z 行判 dontcare 的(写回前瞻)。
# 合一深度模板格式(fmt 260 = Depth32Float_Stencil8)按深度 4 + 模板 1 字节拆:d 行记深度平面,s 行(只挂模板)记模板平面。
# 纹理采样读取(补列,粗估):
# 全屏类通道(绘制顶点数 ≤ 6 且绘制 ≤ 3 次;绘制次数取 PASSDUMP_ALL 的 d 行,没有就取片元程序绑定行数):每个被采样的绑定视图按 min(绑定视图整张字节, 目标像素数 × 每纹素字节);
# 几何类通道:目标像素数 × 通道内片元着色器声明的贴图槽数(取最大)× 被采样贴图的平均每纹素字节(每像素每槽约采一次,材质贴图有 mip)。
# 贴图格式与尺寸取同帧同通道每个描述符的 B 行(同一序号可绑定不同级 / 层的视图),查不到按 4 字节;槽数取 B 库反射 json。
# 用法:tbdr_budget.py <含 PASSDUMP 的日志> [帧号(缺省取第一帧)] [预算 MB=170] [--tsv=全量表路径]
# TSV 不截前 25 名 / 着色器键;带逐次绘制来源、未知贴图分母与合并通道备注。纹理列始终是绑定模型粗估,不是外存实测。
# Per-frame attachment bandwidth budget table (target 120 fps, ≤ 20 GB/s → ≤ 170 MB per frame): from one frame of the DM_NVN_PASSDUMP data stream, list load / store MB per pass,
# sorted by their sum in descending order. Load is counted from P rows with load (clear / dontcare not counted); store is counted from the P rows' attachments, minus those the Z rows judge dontcare (store lookahead).
# Combined depth-stencil formats (fmt 260 = Depth32Float_Stencil8) are split as depth 4 + stencil 1 bytes: d rows record the depth plane, s rows (stencil-only attachment) record the stencil plane.
# Texture sampling reads (supplementary column, rough estimate):
# fullscreen-class passes (draw vertex count ≤ 6 and ≤ 3 draws; draw count from the d rows of PASSDUMP_ALL, or else the number of fragment program binding rows): for each sampled bound view, min(whole bound view bytes, target pixel count × bytes per texel);
# geometry-class passes: target pixel count × number of texture slots declared by the fragment shaders in the pass (take the max) × average bytes per texel of the sampled textures (about one sample per pixel per slot; material textures have mips).
# Texture format and size come from the B row of each descriptor in the same frame and pass (the same serial can bind views of different levels / layers); 4 bytes if not found; slot counts come from the B library reflection json.
# Usage: tbdr_budget.py <log containing PASSDUMP> [frame number (default: first frame)] [budget MB=170] [--tsv=path of the full table]
# The TSV is not truncated to the top 25 / shader keys; it carries per-draw sources, the unknown-texture denominator and merged-pass notes. The texture column is always a rough binding-model estimate, not an external-memory measurement.
import re, sys, collections
BPP = {70: 4, 71: 4, 80: 4, 81: 4, 90: 4, 92: 4, 93: 4, 115: 8, 125: 16, 55: 4, 25: 2, 65: 4, 105: 4, 103: 4, 252: 4, 250: 2, 260: 5, 255: 4, 10: 1, 20: 2, 30: 2, 60: 4, 53: 4}
TSV = next((a[6:] for a in sys.argv[1:] if a.startswith('--tsv=')), None)
args = [a for a in sys.argv[1:] if not a.startswith('--tsv=')]
log = args[0]; FR = args[1] if len(args) > 1 else None; BUDGET = float(args[2]) if len(args) > 2 else 170
P = collections.OrderedDict(); dead = set(); shader = collections.defaultdict(collections.Counter)
TBPP = {10: 1, 20: 2, 25: 2, 30: 2, 53: 4, 55: 4, 60: 4, 65: 8, 70: 4, 71: 4, 80: 4, 81: 4, 90: 4, 92: 4, 93: 4, 103: 8, 105: 8, 115: 8, 125: 16,
130: .5, 131: .5, 132: 1, 133: 1, 134: 1, 135: 1, 140: .5, 141: .5, 142: 1, 143: 1, 150: 1, 151: 1, 152: 1, 153: 1, 250: 2, 252: 4, 255: 4, 260: 4}
texinfo = collections.defaultdict(dict); sampled = collections.defaultdict(set); tgt = {}; maxvc = collections.defaultdict(int); ndraw = collections.defaultdict(int); fskeys = collections.defaultdict(set); fused = set(); att_desc = collections.defaultdict(list)
import os, json; sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))); import dmsh_chain
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
LIB = os.path.join(DM_ROOT, 'build/cache/metal_shader_cache/b-{dmsh_chain.version()}')
def tex_slots(key):
try: return sum(1 for b in json.load(open(f'{LIB}/{key}_b.json'))['bindings'] if b.get('kind') in ('tex', 'samp_tex'))
except Exception: return 4
nm = {}
for ln in open(__file__.rsplit('/', 1)[0] + '/../nvn/shader_map.tsv'):
c = ln.rstrip('\n').split('\t')
if len(c) > 4 and c[0].endswith('.bin'): nm.setdefault(c[3], c[0][:-4])
for l in open(log, errors='replace'):
m = re.search(r'\[pass\] F(\d+) (\w) (\d+) (.*)', l)
if not m: continue
f, k, p, r = m.groups()
if FR is None: FR = f
if f != FR: continue
p = int(p); e = P.setdefault(p, {'att': [], 'load': 0, 'store': 0})
if k == 'P':
a = re.match(r'(c\d+|d|s) ser=(\d+) fmt=(\d+) (\d+)x(\d+)(?:.*? lv(\d+) sl(\d+))?.*?\b(clear|load|dontcare)', r)
if not a: continue
slot, ser, fmt, w, h, lv, sl, act = a.groups(); fmt = int(fmt); lv = int(lv or 0)
b = max(int(w) >> lv, 1) * max(int(h) >> lv, 1) * BPP.get(fmt, 4)
if fmt == 260: b = b // 5 * (4 if slot == 'd' else 1)
e['att'].append((slot, int(ser), lv, int(sl or 0), b, act))
att_desc[p].append(r)
tgt.setdefault(p, max(int(w) >> lv, 1) * max(int(h) >> lv, 1))
elif k == 'B':
b = re.match(r'st\d+ (?:tex|tbuf) reg\d+ tid=(\d+) 实 ser=(\d+) fmt=(\d+) (\d+)x(\d+)x(\d+)', r)
if b:
tid, ser, fmt, w, h, dd = map(int, b.groups())
texinfo[p].setdefault(ser, set()).add((tid, fmt, w, h, dd))
elif k == 'R':
rr = re.match(r'st\d+ ser=(\d+)', r)
if rr: sampled[p].add(int(rr.group(1)))
elif k == 'Z':
z = re.match(r'(c|d|s) ser=(\d+) lv(\d+) sl(\d+) (dontcare|store)', r)
if z and z.group(5) == 'dontcare': dead.add((p, z.group(1), int(z.group(2)), int(z.group(3)), int(z.group(4))))
elif k == 'F' and '合并下一个通道' in r: fused.add(p)
elif k == 'K' and ' st1 ' in f' {r} ':
key = r.split('key=')[1].split()[0].replace('_b', ''); shader[p][nm.get(key, key[:8])] += 1; fskeys[p].add(key)
elif k in ('D', 'd'): # d 行(PASSDUMP_ALL)每次绘制一行,可数绘制次数;D 行只有每通道第一次 | d rows (PASSDUMP_ALL) are one per draw, so draws can be counted; D rows only have the first of each pass
v = re.search(r'vc=(\d+)', r)
if v: maxvc[p] = max(maxvc[p], int(v.group(1)))
if k == 'd': ndraw[p] += 1
ALLD = any(ndraw.values()) # 有逐次绘制行时按绘制次数分类,否则按片元程序绑定行数(只记首次时会把多次小方块误判成全屏类) | classify by draw count when per-draw rows exist, otherwise by the number of fragment program binding rows (when only the first is recorded, many small quads are misclassified as fullscreen class)
rows = []
for p, e in P.items():
ld = sum(b for *_, b, act in e['att'] if act == 'load')
st = sum(b for slot, ser, lv, sl, b, act in e['att'] if (p, slot[0], ser, lv, sl) not in dead)
px = tgt.get(p, 0); tx = 0
nd = ndraw[p] if ALLD else sum(shader[p].values())
if maxvc[p] <= 6 and nd <= 3: # 全屏类(绘制顶点 ≤ 6 且绘制 ≤ 3 次;UI 等多次小方块按几何类算) | fullscreen class (draw vertices ≤ 6 and ≤ 3 draws; many small quads such as UI count as geometry class)
for ser in sampled[p]:
for tid, f, w, h, dd in texinfo[p].get(ser, {(-1, None, 0, 0, 1)}):
tx += min(w * h * dd * TBPP.get(f, 4), px * TBPP.get(f, 4)) if f is not None else px * 4
elif sampled[p]: # 几何类 | geometry class
bp = [TBPP.get(v[1], 4) for s_ in sampled[p] for v in texinfo[p].get(s_, ())] or [4]
tx = px * max([tex_slots(k_) for k_ in fskeys[p]] or [4]) * (sum(bp) / len(bp))
rows.append((ld + st + tx, ld, st, tx, p, ' '.join(f'{slot}:{ser}' + (f'/lv{lv}' if lv else '') for slot, ser, lv, sl, b, act in e['att']), ', '.join(shader[p])[:40]))
tl = sum(r[1] for r in rows) / 1e6; ts = sum(r[2] for r in rows) / 1e6; tt = sum(r[3] for r in rows) / 1e6
print(f'帧 {FR}:通道 {len(rows)} 个;附件 读入 {tl:.1f} + 写回 {ts:.1f} = {tl + ts:.1f} MB(预算 {BUDGET:.0f},超 {tl + ts - BUDGET:+.1f});纹理采样(粗估{"" if ALLD else ",无逐次绘制行,分类偏粗"}){tt:.1f} MB;总带宽 {tl + ts + tt:.1f} MB')
print('总 MB | 附件读入 | 附件写回 | 纹理采样 | 通道 | 附件 | 主要片元着色器')
acc = 0
for t, ld, st, tx, p, att, sh in sorted(rows, reverse=True)[:25]:
acc += t; print(f'{t / 1e6:6.1f} | {ld / 1e6:5.1f} | {st / 1e6:5.1f} | {tx / 1e6:5.1f} | {p} | {att[:52]} | {sh} (累计 {acc / 1e6:.0f})')
if TSV:
import csv
with open(TSV, 'w', encoding='utf-8', newline='') as out:
wr = csv.writer(out, delimiter='\t')
wr.writerow(['frame', 'render_order', 'pass', 'draws', 'draw_source', 'sampling_model', 'target_pixels', 'load_bytes', 'store_bytes', 'texture_est_bytes', 'total_est_bytes', 'unknown_textures', 'unknown_formats', 'texture_views', 'sampled_serials', 'fragment_keys', 'fragment_names', 'attachments', 'attachment_details', 'note'])
for order, (total, ld, st, tx, p, att, _) in enumerate(rows):
nd = ndraw[p] if ALLD else sum(shader[p].values())
source = 'PASSDUMP_ALL' if ndraw[p] else 'clear_only' if not maxvc[p] else 'shader_bindings'
model = 'small_draw' if maxvc[p] <= 6 and nd <= 3 else 'geometry'
views = [v for s_ in sampled[p] for v in texinfo[p].get(s_, ())]
wr.writerow([FR, order, p, nd, source, model, tgt.get(p, 0), int(ld), int(st), int(tx), int(total),
len(sampled[p] - texinfo[p].keys()), sum(v[1] not in TBPP for v in views), len(views), ','.join(map(str, sorted(sampled[p]))), ','.join(sorted(fskeys[p])), ','.join(shader[p]), att, '; '.join(att_desc[p]),
'绑定模型粗估;含tile绑定,不是外存实测' if p in fused else '绑定模型粗估,不是外存实测'])
+49
View File
@@ -0,0 +1,49 @@
# TBDR 读入可省的候选:DM_NVN_PASSDUMP 的 P(附件)与 D(通道首次绘制特征)行。颜色附件读入为候选的条件:
# 首绘是单实例三角形 / 四边形 / 条带、顶点 3–6、剪裁与视口覆盖整个目标、该附件不混合且写掩码满、深度测试关或 ALWAYS、模板关。
# 覆盖是否真为全屏取决于顶点着色器,候选须再用哨兵色实验(读入改成清成哨兵色,比最终画面)证实。
# Candidates for skippable TBDR loads: the P (attachment) and D (first-draw features of a pass) rows of DM_NVN_PASSDUMP. Conditions for a color attachment load to be a candidate:
# the first draw is a single-instance triangle / quad / strip with 3–6 vertices, scissor and viewport cover the whole target, the attachment is not blended and has a full write mask, depth test off or ALWAYS, stencil off.
# Whether coverage is truly fullscreen depends on the vertex shader; candidates must still be confirmed by a sentinel color experiment (change the load into a clear to the sentinel color and compare the final image).
import re, sys, collections
BPP={70:4,71:4,80:4,81:4,90:4,92:4,93:4,115:8,125:16,55:4,25:2,65:4,105:4,103:4,252:4,250:2,260:5,255:4,10:1,20:2,30:2,60:4,53:4}
P=collections.defaultdict(list); D={}; FA=None
for l in open(sys.argv[1]):
l=l.strip()
m=re.match(r'\[pass\] F(\d+) P (\d+) (c\d+|d) ser=(\d+) fmt=(\d+) (\d+)x(\d+)(?:.*? lv(\d+))?.*?(clear|load|dontcare)$',l)
if m:
f,p,slot,s,fmt,w,h,lv,act=m.groups()
if FA is None: FA=int(f)
if int(f)!=FA: continue
lv=int(lv or 0); P[int(p)].append((slot,int(s),int(fmt),act,max(int(w)>>lv,1)*max(int(h)>>lv,1)*BPP.get(int(fmt),4)))
continue
m=re.match(r'\[pass\] F(\d+) D (\d+) prim=(\d+) vc=(\d+) inst=(\d+) blend=(\S+) wm=(\S+) dt=(\d) dw=(\d) df=(\d+) st=(\d) sc=(\d+),(\d+),(\d+),(\d+) tgt=(\d+)x(\d+) vp=([-\d.]+),([-\d.]+),([-\d.]+),([-\d.]+)',l)
if m and FA is not None and int(m.group(1))==FA:
g=m.groups(); D[int(g[1])]=dict(prim=int(g[2]),vc=int(g[3]),inst=int(g[4]),blend=int(g[5],16),wm=int(g[6],16),dt=int(g[7]),df=int(g[9]),st=int(g[10]),
sc=tuple(map(int,g[11:15])),tgt=(int(g[15]),int(g[16])),vp=tuple(map(float,g[17:21])))
ALWAYS=8
tot=cand=0; rows=[]
for p,atts in P.items():
for slot,s,fmt,act,b in atts:
if act!='load': continue
tot+=b
d=D.get(p); why=[]
if not d: why.append('无绘制')
else:
W,H=d['tgt']
if d['prim'] not in (4,5,7) or not 3<=d['vc']<=6 or d['inst']>1: why.append('非单个全屏图元')
if d['sc']!=(0,0,W,H): why.append('剪裁非整屏')
if d['vp'][:2]!=(0,0) or d['vp'][2]<W or d['vp'][3]<H: why.append('视口非整屏')
if slot=='d': why.append('深度读入(不判)')
else:
i=int(slot[1:])
if d['blend']>>i&1: why.append('混合')
if (d['wm']>>(4*i))&0xf!=0xf: why.append('写掩码不满')
if d['dt'] and d['df']!=ALWAYS: why.append('深度测试')
if d['st']: why.append('模板测试')
if not why: cand+=b
rows.append((p,slot,s,fmt,b,'候选' if not why else '/'.join(why)))
print('帧 %d:附件读入 %.1f MB;首绘全屏无依赖的候选 %.1f MB(%.0f%%)'%(FA,tot/1e6,cand/1e6,100*cand/tot if tot else 0))
c=collections.Counter(r[5] for r in rows)
for k,v in c.most_common(): print(' %-28s %3d 个 %.1f MB'%(k,v,sum(r[4] for r in rows if r[5]==k)/1e6))
for r in rows:
if r[5]=='候选': print(' 候选 通道 %d %s ser=%d fmt%d %.1f MB'%(r[0],r[1],r[2],r[3],r[4]/1e6))
+27
View File
@@ -0,0 +1,27 @@
# 相邻通道同一组附件(序号 + mip 级 + 层)且后者全部读入:中间的切分若非必要,合并可省一整读一整写
# Adjacent passes with the same set of attachments (serial + mip level + layer) where the later one loads all of them: if the split in between is not necessary, merging saves one full load and one full store
import re, sys, collections
BPP={70:4,71:4,80:4,81:4,90:4,92:4,93:4,115:8,125:16,55:4,25:2,65:4,105:4,103:4,252:4,250:2,260:5,255:4,10:1,20:2,30:2,60:4,53:4}
passes=collections.OrderedDict(); order=[]; between=collections.defaultdict(set)
FA=None; last=None
for l in open(sys.argv[1]):
m=re.match(r'\[pass\] F(\d+) P (\d+) (c\d+|d) ser=(\d+) fmt=(\d+) (\d+)x(\d+)(?:.*? lv(\d+))?(?:.*? sl(\d+))?.*?(clear|load)$',l.strip())
if m:
f,p,slot,s,fmt,w,h,lv,sl,act=m.groups(); f=int(f); p=int(p)
if FA is None: FA=f
if f!=FA: break
lv=int(lv or 0); b=max(int(w)>>lv,1)*max(int(h)>>lv,1)*BPP.get(int(fmt),4)
if p not in passes: passes[p]=[]; order.append(p)
passes[p].append((slot,int(s),lv,int(sl or 0),act,b)); last=p
m=re.match(r'\[pass\] F(\d+) R (\d+) st\d+ ser=(\d+)',l.strip())
if m and int(m.group(1))==FA: between[int(m.group(2))].add(int(m.group(3))) # 该通道里采样的贴图 | textures sampled in this pass
key=lambda p: tuple(sorted((a[0],a[1],a[2],a[3]) for a in passes[p]))
n=0; sv=0; ex=[]
for a,b in zip(order,order[1:]):
if key(a)==key(b) and all(x[4]=='load' for x in passes[b]):
sers={x[1] for x in passes[a]}
hazard = bool(sers & between[b]) # 后一通道把自己的附件当贴图采样:不能合并 | the later pass samples its own attachment as a texture: cannot merge
bb=sum(x[5] for x in passes[b])
if not hazard: n+=1; sv+=2*bb; ex.append((a,b,bb))
print('帧 %d:通道 %d 个;相邻同附件且后者全读入、且后者不采样这些附件的切分 %d 处,合并可省 %.1f MB/帧(一读一写)'%(FA,len(order),n,sv/1e6))
for a,b,bb in ex[:12]: print(' %d→%d:%s %.1f MB'%(a,b,' '.join('%s:ser%d'%(x[0],x[1]) for x in passes[b]),bb/1e6))
+36
View File
@@ -0,0 +1,36 @@
# TBDR 可证省的写出:DM_NVN_PASSDUMP 两帧数据流。帧 A 的每个附件写出(Store),若在该贴图下次被清除之前没有任何读取
# (采样 R、作为附件读入 load、出图 X),则可证为不需要(DontCare)。附件按(贴图, 级, 层)区分:清别的级 / 层不算清它;
# 采样 R 只记整张贴图,按读取算(保守)。拷贝 / 清贴图不在转储里,此处看不到,结果是上限,以运行时 DM_NVN_STORESCAN 的 Z 行为准。前瞻到帧 B 结束,跨帧历史读取算「需要」。读入不判(需证全覆盖)。
# Provably skippable TBDR stores: two frames of the DM_NVN_PASSDUMP data stream. Each attachment store (Store) in frame A is provably unnecessary (DontCare) if nothing reads it before that texture is next cleared
# (sample R, load as an attachment, present X). Attachments are distinguished by (texture, level, layer): clearing another level / layer does not count as clearing it;
# sample R only records the whole texture and is counted as a read (conservative). Copies / texture clears are not in the dump and cannot be seen here, so the result is an upper bound; the Z rows of runtime DM_NVN_STORESCAN are authoritative. Lookahead runs to the end of frame B; cross-frame history reads count as "needed". Loads are not judged (that requires proving full coverage).
import re, sys, collections
L=[l.split(None,2)[2].strip() if False else l.strip() for l in open(sys.argv[1])]
BPP={70:4,71:4,80:4,81:4,90:4,92:4,93:4,115:8,125:16,55:4,25:2,65:4,105:4,103:4,252:4,250:2,260:5,255:4,10:1,20:2,30:2,60:4}
ev=[] # (frame, kind, pass, ser, load|clear, bytes, fmt, w, h, slot, (lv, sl))
for l in L:
m=re.match(r'\[pass\] F(\d+) P (\d+) (c\d+|d) ser=(\d+) fmt=(\d+) (\d+)x(\d+)(?:.*? lv(\d+) sl(\d+))?.*?(clear|load|dontcare)$',l)
if m:
f,p,slot,s,fmt,w,h,lv,sl,act=m.groups(); fmt=int(fmt); lv=int(lv or 0); sl=int(sl or 0); w=max(int(w)>>lv,1); h=max(int(h)>>lv,1)
ev.append((int(f),'P',int(p),int(s),act,int(w)*int(h)*BPP.get(fmt,4),fmt,int(w),int(h),slot,(lv,sl))); continue
m=re.match(r'\[pass\] F(\d+) R (\d+) st\d+ ser=(\d+)',l)
if m: ev.append((int(m.group(1)),'R',int(m.group(2)),int(m.group(3)),'',0,0,0,0,'',None)); continue
m=re.match(r'\[pass\] F(\d+) X ser=(\d+)',l)
if m: ev.append((int(m.group(1)),'X',-1,int(m.group(2)),'',0,0,0,0,'',None))
FA=min(e[0] for e in ev)
tot=0; save=0; nst=0; nsave=0; rows=collections.Counter(); load_b=0
for i,e in enumerate(ev):
if e[0]!=FA or e[1]!='P': continue
nst+=1; tot+=e[5]
if e[4]=='load': load_b+=e[5]
need=False
for g in ev[i+1:]:
if g[3]!=e[3]: continue
if g[1]=='P' and g[2]==e[2]: continue # 同一通道的其余附件行 | the remaining attachment rows of the same pass
if g[1] in ('R','X'): need=True; break
if g[1]=='P' and g[10]!=e[10]: continue # 同贴图别的级 / 层作附件:与它无关 | another level / layer of the same texture used as an attachment: unrelated to it
if g[1]=='P': need = g[4]=='load'; break # 下次作附件:读入则需要,清除 / 读入可省(dontcare)则不需要 | next use is as an attachment: needed if loaded, not needed if cleared / load skippable (dontcare)
if not need:
save+=e[5]; nsave+=1; rows[(e[9][0],e[6],e[7],e[8])]+=e[5]
print('帧 %d:附件写出 %d 个、%.1f MB;可证不需要 %d 个、%.1f MB(%.0f%%);附件读入 %.1f MB(不判)'%(FA,nst,tot/1e6,nsave,save/1e6,100*save/tot if tot else 0,load_b/1e6))
for k,v in rows.most_common(10): print(' %s fmt%d %dx%d:%.1f MB'%(k[0]=='d' and '深度' or '颜色',k[1],k[2],k[3],v/1e6))