Android port (Adreno): Vulkan backend, GameActivity app, touch HUD, lifecycle, minimap quest goals

- host/android: Vulkan replay backend (nvn_vk.c) with pipeline/descriptor caching, ADPF,
  AChoreographer present link; Linux compat layer; Makefile.android (headless dmhost + APK lib)
- android/app: GameActivity shell without Gradle (build_apk.sh), AAudio output, touch HUD port
  (touch_app.c + TouchOverlay.java, three layers: body / joystick / minimap goals),
  lifecycle save-on-background like iOS, art_from_ipa.py for touch / HUD / mapgoal art
- touch: shared touch controls moved from ios/Sources to dm/touch
- patch_nso.py Android ruleset, dmsh_vk.py shader pack, DM_TOUCH_PRODUCT defaults
- hle_audio: AAudio resume waits through STARTING and reopens once on failure
- .gitignore: local resources/ (original game data) never committed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-14 14:55:05 +09:00
co-authored by Claude Opus 5.5
parent 5bc5a01087
commit 4d91f80bae
106 changed files with 7009 additions and 181 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
dmsh_xlate.dll aff3b70cff6bf29e
Ryujinx.Graphics.Shader.dll 72886c0b30bc0016
Ryujinx.Common.dll 614dced78b44547d
xlate_source 1cc46907ca1ee8d0
xlate_source d379d76ef969729f
spirv-cross c95d3fc88f6ae5f5
metal_macosx Apple metal version 32023.883 (metalfe-32023.883)
metal_iphoneos Apple metal version 32023.883 (metalfe-32023.883)
+378
View File
@@ -0,0 +1,378 @@
#!/usr/bin/env python3
# Vulkan 路线离线出包(Android):Switch 原版着色器 → SPIR-V(dmsh_xlate,Ryujinx 翻译器)→ 直接给 Vulkan 用,不经 spirv-cross / Metal。
# 与 dmsh_build.py 共用作业构造(作答表 nvn/shader_facts.tsv、映射表 nvn/shader_map.tsv、c1、内嵌着色器);反射直接从 SPIR-V 的名字与修饰里读,
# 资源分类与 dmsh_build.reflect 同口径(Ryujinx 的资源名 spirv-cross 原样保留进 MSL,所以同一套名字规则在 SPIR-V 上同样成立)。
# 改写:描述符组号按阶段分开——顶点 / 计算 = 0,像素 = 1(Ryujinx 一律放进第 0 组,绑定号各阶段都从 1 起,同一管线里会撞)。
# 用法:dmsh_vk.py <Switch 着色器包目录> <输出目录> [键…](不给键 = 全部) 环境:XLATE=翻译工具,MAIN=Switch main NSO(内嵌着色器),J=并发,SPIRV_VAL=校验工具
# 产物:<输出目录>/<键>.spv(已改组号)、<输出目录>/<键>.vk.json(反射)、<输出目录>/_vk_build.json(逐键结果);
# <输出目录>/rt/:设备端运行时缓存(nvn_vk.c 读)= shader_index.bin(控制段 → 键)+ <键>.vkmeta(绑定表)+ <键>.spv.gz
# PACK_ONLY=1 只按已有 .spv / .vk.json 重出 rt/;GLSLC=glslc 时一并编译 main 内嵌的 4 个计数报告内核(nvn_builtin.h)
# SB_ALIGN=宿主存储缓冲偏移对齐(缺省 64 = Adreno):翻译器按 base & -SB_ALIGN 求 SSBO 偏移,vkmeta 绑定标志位 1 告诉宿主可下对齐绑定、免拷贝;16 = 与 iOS 同样的翻译
# Vulkan-route offline build (Android): original Switch shaders → SPIR-V (dmsh_xlate, the Ryujinx translator) → used by Vulkan directly, no spirv-cross / Metal.
# Shares job construction with dmsh_build.py (answer table nvn/shader_facts.tsv, mapping table nvn/shader_map.tsv, c1, embedded shaders); reflection is read straight from SPIR-V names and decorations,
# resource classification follows dmsh_build.reflect (spirv-cross keeps Ryujinx's resource names in the MSL unchanged, so the same naming rules hold on SPIR-V).
# Rewrite: descriptor set numbers are split by stage - vertex / compute = 0, pixel = 1 (Ryujinx puts everything in set 0 with binding numbers starting at 1 in every stage, which collide within one pipeline).
# Usage: dmsh_vk.py <Switch shader package dir> <output dir> [key...] (no keys = all) Environment: XLATE=translator, MAIN=Switch main NSO (embedded shaders), J=concurrency, SPIRV_VAL=validator
# Output: <output dir>/<key>.spv (set numbers rewritten), <output dir>/<key>.vk.json (reflection), <output dir>/_vk_build.json (per-key results);
# <output dir>/rt/: the on-device runtime cache (read by nvn_vk.c) = shader_index.bin (control segment → key) + <key>.vkmeta (binding table) + <key>.spv.gz
# PACK_ONLY=1 only re-emits rt/ from the existing .spv / .vk.json; with GLSLC=glslc the 4 counter-report kernels embedded in main (nvn_builtin.h) are compiled too
# SB_ALIGN=host storage buffer offset alignment (default 64 = Adreno): the translator takes SSBO offsets from base & -SB_ALIGN, and vkmeta binding flag bit 1 tells the host it may bind aligned down without copying; 16 = the same translation as iOS
import os, sys, re, json, struct, gzip, hashlib, shutil, subprocess, tempfile, collections, concurrent.futures as cf
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE); import dmsh_facts
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work')
dm_dir, out = sys.argv[1:3]; want = set(sys.argv[3:])
XLATE = os.environ.get('XLATE', f'{DM_ROOT}/build/gfx/dmsh_xlate/dmsh_xlate')
MAIN = os.environ.get('MAIN', f'{DM_ROOT}/data/switch/3.3.94012/Update/ExeFS/main')
SPIRV_VAL = os.environ.get('SPIRV_VAL', shutil.which('spirv-val') or '')
MAP = os.path.join(HERE, '../nvn/shader_map.tsv')
FACTS = dmsh_facts.load()
if not FACTS: sys.exit('【红】没有作答表 nvn/shader_facts.tsv')
TEX_BASE, SAMP_BASE, IMG_BASE = 0x168, 0x568, 0x120
SET_OF = {'vs': 0, 'cs': 0, 'ps': 1}
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)]
loc, stage_of = {}, {}
for ln in open(MAP):
c = ln.rstrip('\n').split('\t')
if len(c) > 4 and c[0].endswith('.bin'): loc.setdefault(c[3], (c[0], int(c[1])))
if len(c) > 4 and c[0].startswith('main.rodata@'):
loc.setdefault(c[3], (c[0], int(c[0].split('@')[1], 16))); stage_of[c[3]] = {'顶点': 'vs', '像素': 'ps'}[c[2]]
def main_rec(mi, o):
# 同 dmsh_build.main_rec:内嵌代码区紧贴控制段之前 | same as dmsh_build.main_rec: the embedded code area sits right before the control segment
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):
# 同 dmsh_build.job_for | same as dmsh_build.job_for
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)
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',
'sb_align': int(os.environ.get('SB_ALIGN', '64'))} # Adreno minStorageBufferOffsetAlignment;翻译器按 base & -64 求偏移 | translator takes offsets from base & -64
if key not in FACTS: j['pc_missing'] = True; return j, c1
j.update(FACTS[key])
return j, c1
def decode_tex(name):
# 同 dmsh_build.decode_tex | same as dmsh_build.decode_tex
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):
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
# ---- SPIR-V 解析 | SPIR-V parsing ----
OP_NAME, OP_DECORATE, OP_VARIABLE, OP_TYPE_POINTER, OP_ENTRY, OP_EXEC_MODE = 5, 71, 59, 32, 15, 16
OP_TYPE_IMAGE, OP_TYPE_SAMPLER, OP_TYPE_SAMPLED_IMAGE, OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT = 25, 26, 27, 28, 29, 30
DEC_BINDING, DEC_SET, DEC_LOCATION, DEC_BUILTIN = 33, 34, 30, 11
SC_UNIFORM_CONSTANT, SC_INPUT, SC_UNIFORM, SC_OUTPUT, SC_STORAGE_BUFFER = 0, 1, 2, 3, 12
def spv_insts(words):
o = 5
while o < len(words):
n, op = words[o] >> 16, words[o] & 0xffff
if not n or o + n > len(words): raise ValueError(f'SPIR-V 指令越界 @{o}')
yield o, op, words[o + 1:o + n]; o += n
def spv_str(ops):
b = struct.pack(f'<{len(ops)}I', *ops); return b[:b.index(0)].decode()
def reflect_spv(key, stage, words, res):
names, deco, types, var = {}, collections.defaultdict(dict), {}, {}
for o, op, a in spv_insts(words):
if op == OP_NAME: names[a[0]] = spv_str(a[1:])
elif op == OP_DECORATE and len(a) >= 2: deco[a[0]][a[1]] = a[2] if len(a) > 2 else 1
elif 19 <= op <= 39: types[a[0]] = (op, a[1:])
elif op == OP_VARIABLE: var[a[1]] = (a[0], a[2])
def pointee(tid):
t = types.get(tid); return t[1][1] if t and t[0] == OP_TYPE_POINTER else None
def base(tid):
while tid in types and types[tid][0] in (OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY): tid = types[tid][1][0]
return tid
def desc_type(sc, tid):
"""VkDescriptorType:0 采样器、1 组合、2 采样图像、3 存储图像、4 uniform 纹素缓冲、5 存储纹素缓冲、6 uniform 缓冲、7 存储缓冲 | VkDescriptorType numbering"""
t = types.get(base(tid))
if sc == SC_UNIFORM: return 7 if deco[base(tid)].get(3) else 6 # BufferBlock(3) 旧式存储缓冲 | BufferBlock (3) is the legacy storage buffer form
if sc == SC_STORAGE_BUFFER: return 7
if not t: return None
if t[0] == OP_TYPE_SAMPLER: return 0
if t[0] == OP_TYPE_SAMPLED_IMAGE:
im = types[t[1][0]]; return 4 if im[1][1] == 5 else 1 # Dim Buffer = 5
if t[0] == OP_TYPE_IMAGE:
dim, sampled = t[1][1], t[1][5]
if dim == 5: return 4 if sampled == 1 else 5
return 2 if sampled == 1 else 3
return None
binds = []
sb_sorted = sorted(res['sbufs'], key=lambda b: b['binding'])
sb_by_binding = {b['binding']: (i, b) for i, b in enumerate(sb_sorted)}
sbase = {'vs': 0x110, 'cs': 0x310, 'ps': 0x510}[stage]
for vid, (ptype, sc) in var.items():
if sc not in (SC_UNIFORM_CONSTANT, SC_UNIFORM, SC_STORAGE_BUFFER) or DEC_BINDING not in deco[vid]: continue
nm = names.get(vid, ''); ty = desc_type(sc, pointee(ptype))
tdef = types.get(pointee(ptype)); count = 1
if tdef and tdef[0] == OP_TYPE_ARRAY: count = -1 # 描述符数组:Ryujinx 只在无绑定贴图时出,这里不支持 | descriptor array: Ryujinx only emits it for bindless textures; unsupported here
e = {'name': nm, 'binding': deco[vid][DEC_BINDING], 'set': deco[vid].get(DEC_SET, 0), 'vk_type': ty, 'count': count, 'var': vid}
if nm == 'support_buffer': e['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):
idx, b = sb_by_binding.get(e['binding'], (None, None))
e.update(kind='sbuf', index=idx)
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)
else: e['reg'] = (off - sbase) // 16 if off is not None and 0 <= off - sbase < 0x100 and (off - sbase) % 16 == 0 else None
e['rw'] = bool(b and b['flags'] & 2)
elif ty == 0:
t, s, hty = decode_tex(nm[:-5] if nm.endswith('Smplr') else nm) or (None, None, 0)
e.update(kind='samp', reg=s) if hty else e.update(kind='samp_tex', reg=t)
else:
d = decode_tex(nm)
if not d: e['kind'] = '?'
else:
img = bool(re.match(r'[a-z]+_i', nm))
e.update(kind='img' if img else ('tbuf' if ty in (4, 5) else 'tex'), reg=d[0])
if not img and ty == 1: # 组合采样:采样器号取同一句柄(类型 0 = 贴图槽句柄高位) | combined: sampler from the same handle (type 0 = high bits of the texture slot's handle)
e['samp'] = d[1] if d[2] else None; e['samp_from_tex'] = not d[2]
binds.append(e)
binds.sort(key=lambda b: b['binding'])
inputs = sorted(deco[v][DEC_LOCATION] for v, (_, sc) in var.items() if sc == SC_INPUT and DEC_LOCATION in deco[v] and DEC_BUILTIN not in deco[v])
outputs = sorted(deco[v][DEC_LOCATION] for v, (_, sc) in var.items() if sc == SC_OUTPUT and DEC_LOCATION in deco[v] and DEC_BUILTIN not in deco[v])
return binds, inputs, outputs
def drv_reads(words, binds):
"""对驱动段 c0 / c2 的访问:OpAccessChain(var, 0, 常量 vec4 下标, 常量分量) → 字节偏移;非常量 → 动态 | accesses to driver segments c0 / c2"""
consts, out = {}, {}
for o, op, a in spv_insts(words):
if op == 43 and len(a) == 3: consts[a[1]] = a[2]
drv = {b['var']: b['bank'] for b in binds if b['kind'] == 'drvcb'}
for o, op, a in spv_insts(words):
if op in (65, 66) and len(a) >= 3 and a[2] in drv:
d = out.setdefault(str(drv[a[2]]), {'offsets': set(), 'dynamic': False})
idx = a[3:]
if len(idx) >= 2 and all(i in consts for i in idx[:3]): d['offsets'].add(consts[idx[1]] * 16 + (consts[idx[2]] * 4 if len(idx) > 2 else 0))
else: d['dynamic'] = True
return {k: {'offsets': sorted(v['offsets']), 'dynamic': v['dynamic']} for k, v in out.items()}
def set_rewrite(words, stage):
"""组号按阶段改写;去掉 Ryujinx 无条件声明、实际没用到的能力(Float64 / Int64 / 像素互锁 / 绘制参数),免得驱动按缺特性拒收
Rewrite set numbers per stage; drop capabilities Ryujinx declares unconditionally but never uses (Float64 / Int64 / pixel interlock / draw parameters), so drivers lacking the feature do not reject the module"""
s = SET_OF[stage]; used = set(); keep = []
for o, op, a in spv_insts(words):
if op == 22 and a[1] == 64: used.add(10) # OpTypeFloat 64 → Float64
if op == 21 and a[1] == 64: used.add(11) # OpTypeInt 64 → Int64
if op in (5364, 5365): used.add(5378) # Begin / EndInvocationInterlockEXT
if op == OP_DECORATE and len(a) == 3 and a[1] == DEC_BUILTIN and a[2] in (4424, 4425, 4426): used.add(4427) # BaseVertex / BaseInstance / DrawIndex
drop = {10, 11, 5378, 4427} - used
have = {a[0] for o, op, a in spv_insts(words) if op == 17}
unk = any(op == OP_TYPE_IMAGE and a[6] == 2 and a[7] == 0 for o, op, a in spv_insts(words)) # 无格式存储图像 | storage image with Unknown format
add = [c for c in (55, 56) if unk and c not in have] # Storage Image Read / WriteWithoutFormat(Adreno 两个特性都有 | Adreno has both features)
for o, op, a in spv_insts(words):
if op == 17 and add:
for c in add: keep.extend([2 << 16 | 17, c])
add = []
ins = list(words[o:o + 1 + len(a)])
if op == 17 and a[0] in drop: continue
if op == 10 and spv_str(a) == 'SPV_EXT_fragment_shader_interlock' and 5378 in drop: continue
if op == 16 and a[1] in (5366, 5367, 5368, 5369, 5370, 5371) and 5378 in drop: continue # 互锁执行模式 | interlock execution modes
if op == OP_DECORATE and len(a) == 3 and a[1] == DEC_SET: ins[3] = s
keep.extend(ins)
return list(words[:5]) + keep
# 翻译器对每个着色器都声明 GroupNonUniform{Vote,Ballot,Shuffle}(cap 62/64/65),实际只有少数 ps / cs 用到;
# Adreno 的 subgroup 只支持 fragment / compute,顶点着色器带着这些声明会被拒,所以没用到 subgroup 指令 / 内建量的就把声明去掉
# The translator declares GroupNonUniform{Vote,Ballot,Shuffle} (cap 62/64/65) on every shader but only a few ps / cs use them;
# Adreno supports subgroups only in fragment / compute and a vertex shader carrying them is rejected, so drop the declarations when no subgroup instruction / builtin is used
SUBGROUP_CAPS = set(range(61, 69))
SUBGROUP_BUILTINS = {36, 37, 38, 39, 40, 41, 4416, 4417, 4418, 4419, 4420}
def strip_subgroup(words):
used = False
for o, op, a in spv_insts(words):
if 333 <= op <= 366 or op in (4421, 4422, 4428, 4429, 4430, 4431, 4432) or \
(op == 71 and len(a) >= 3 and a[1] == DEC_BUILTIN and a[2] in SUBGROUP_BUILTINS): used = True; break
if used: return words
keep = [x for o, op, a in spv_insts(words) for x in words[o:o + (words[o] >> 16)] if not (op == 17 and a[0] in SUBGROUP_CAPS)]
return list(words[:5]) + keep
def finish(key, w, j, c1, name, k):
if j['stage'] not in SET_OF: return 'skip stage ' + j['stage'], None # 外壳 / 域各 1 个,Metal 回放层同样不用 | one hull / one domain shader; the Metal replay does not use them either
spv = os.path.join(w, key + '.spv')
if not os.path.exists(spv): return 'no spv', None
res = json.load(open(os.path.join(w, key + '.res.json')))
data = open(spv, 'rb').read(); words = list(struct.unpack(f'<{len(data) // 4}I', data))
if words[0] != 0x07230203: return 'bad magic', None
binds, inputs, outputs = reflect_spv(key, j['stage'], words, res)
words = set_rewrite(words, j['stage'])
words = strip_subgroup(words)
open(os.path.join(out, key + '.spv'), 'wb').write(struct.pack(f'<{len(words)}I', *words))
caps = sorted({a[0] for o, op, a in spv_insts(words) if op == 17})
exts = sorted({spv_str(a) for o, op, a in spv_insts(words) if op == 10})
refl = {'key': key, 'stage': j['stage'], 'set': SET_OF[j['stage']], 'source': f'{name}#{k}', 'c1': c1.hex(),
'local': j.get('local'), 'shared': j.get('shared', 0), 'notes': res['notes'] + (['pc_missing'] if j.get('pc_missing') else []),
'bindings': [{x: v for x, v in b.items() if x not in ('var', 'set')} for b in binds], 'inputs': inputs, 'outputs': outputs,
'sb_align': res.get('sb_align', 16), 'frag_out_map': res.get('frag_out_map'), 'uses_frag_coord': res.get('uses_frag_coord'),
'drv_reads': drv_reads(words, binds), 'caps': caps, 'exts': exts}
bad = [b for b in binds if b['kind'] == '?' or b['vk_type'] is None or b['count'] != 1 or
(b['kind'] in ('cbuf', 'samp', 'samp_tex', 'tex', 'img', 'tbuf', 'sbuf', 'ubo_ptr') and b.get('reg') is None)]
if bad: refl['unresolved'] = [b['name'] for b in bad]
json.dump(refl, open(os.path.join(out, key + '.vk.json'), 'w'), ensure_ascii=False, indent=1)
if SPIRV_VAL:
r = subprocess.run([SPIRV_VAL, '--target-env', 'vulkan1.1', os.path.join(out, key + '.spv')], capture_output=True, text=True)
if r.returncode: return 'spirv-val: ' + (r.stdout + r.stderr).strip().splitlines()[0][:140], refl
return ('unresolved' if bad else 'ok'), refl
# ---- 设备端运行时缓存(nvn_vk.c 的 RHeader / RBinding 布局) | on-device runtime cache (RHeader / RBinding layout of nvn_vk.c) ----
STAGE_NO = {'vs': 0, 'ps': 1, 'cs': 5}
# 资源种类码 | resource kind codes: 1 support 2 uniform 3 storage 4 texture 6 image 7 c1 8 driver table 9 uniform via storage 10 texel buffer
KIND_NO = {'support': 1, 'cbuf': 2, 'sbuf': 3, 'tex': 4, 'img': 6, 'c1': 7, 'drvcb': 8, 'ubo_ptr': 9, 'tbuf': 10}
# 计数报告内核(nvn_builtin.h 的 Vulkan 版):u64 用 uvec2 进位算,免 Int64 | counter-report kernels (Vulkan form of nvn_builtin.h): u64 as uvec2 with carry, no Int64
BUILTIN = {'d0f769bb916bbba9': (0x1df10e8, 'ST(LD(id * 4u));'),
'16479cc6d75c2b28': (0x1df1a94, 'ST(LD(id * 4u + 2u));'),
'0687e2ef95133577': (0x1df2440, 'ST(SUB(LD(id * 8u + 4u), LD(id * 8u)));'),
'4df5909e6dabee05': (0x1df2dec, 'ST(SUB(LD(id * 8u + 6u), LD(id * 8u + 2u)));')}
BUILTIN_GLSL = """#version 450
layout(local_size_x = 32) in;
layout(set = 0, binding = 0) uniform U { uint n; } u;
layout(set = 0, binding = 1) readonly buffer S { uint s[]; };
layout(set = 0, binding = 2) writeonly buffer D { uint d[]; };
#define LD(w) uvec2(s[w], s[(w) + 1u])
#define ST(v) { uvec2 v_ = v; d[id * 2u] = v_.x; d[id * 2u + 1u] = v_.y; }
uvec2 SUB(uvec2 a, uvec2 b) { uint borrow; uint lo = usubBorrow(a.x, b.x, borrow); return uvec2(lo, a.y - b.y - borrow); }
void main() { uint id = (gl_WorkGroupID.x << 5) + gl_LocalInvocationID.x; if (id >= u.n) return; BODY }
"""
def vkmeta(refl, spv_size):
st = STAGE_NO[refl['stage']]; bs = refl['bindings']
attrs = [(l, 0) for l in refl['inputs']] if refl['stage'] == 'vs' else []
c1 = bytes.fromhex(refl['c1']).rstrip(b'\0')
c1 += bytes(-len(c1) % 4)
caps = refl['caps']; local = refl.get('local') or [0, 0, 0]
fout = refl.get('frag_out_map'); fout = 0 if fout is None else fout
if len(bs) > 64 or len(attrs) > 32 or len(caps) > 32 or len(c1) > 4096: raise ValueError(f"{refl['key']} 超出 vkmeta 上限")
h = struct.pack('<11I', 0x4d4b5644, 1, st, len(bs), len(attrs), len(c1), len(caps), *local[:3], fout) + struct.pack('<I', spv_size)
for b in bs:
k = KIND_NO[b['kind']]
slot = 0 if k in (1, 7) else b['bank'] if k == 8 else b['reg']
samp = b['samp'] if k == 4 and b.get('samp') is not None else -1
# 位 0 可写;位 1 着色器偏移相对 base & -64(翻译器实际答的对齐),宿主可下对齐绑定 | bit 0 writable; bit 1 shader offsets are relative to base & -64 (the alignment the translator actually used), so the host may bind aligned down
flags = (int(bool(b.get('rw'))) | (2 if refl.get('sb_align', 16) == 64 else 0)) if k == 3 else 0
h += struct.pack('<4I2i2I', SET_OF[refl['stage']], b['binding'], b['vk_type'], k, slot, samp, 1, flags)
for a in attrs: h += struct.pack('<2I', *a)
h += struct.pack(f'<{len(caps)}I', *caps) + c1
return h
def emit_runtime(entries):
"""entries: [(键, 控制段 0x880 字节, 反射, SPIR-V 字节)] → <out>/rt | entries: [(key, 0x880-byte control segment, reflection, SPIR-V bytes)] → <out>/rt"""
rt = os.path.join(out, 'rt'); os.makedirs(rt, exist_ok=True)
idx = [struct.pack('<3I', 0x494b5644, 1, len(entries))]
for key, ctl, refl, spv in entries:
assert len(ctl) == 0x880 and len(key) == 16
words = strip_subgroup(list(struct.unpack(f'<{len(spv) // 4}I', spv))) # PACK_ONLY 读的旧产物也要剔 | old outputs read by PACK_ONLY need it too
spv = struct.pack(f'<{len(words)}I', *words); refl = dict(refl, caps=sorted({a[0] for o, op, a in spv_insts(words) if op == 17}))
idx.append(key.encode() + struct.pack('<I', STAGE_NO[refl['stage']]) + ctl)
open(os.path.join(rt, key + '.vkmeta'), 'wb').write(vkmeta(refl, len(spv)))
open(os.path.join(rt, key + '.spv.gz'), 'wb').write(gzip.compress(spv, 9, mtime=0))
open(os.path.join(rt, 'shader_index.bin'), 'wb').write(b''.join(idx))
print(f'运行时缓存:{len(entries)} 条 → {rt}')
def builtin_entries(mi):
glslc = os.environ.get('GLSLC')
if not glslc: print('【黄】没给 GLSLC,跳过 4 个内嵌计数报告内核'); return []
res = []
for key, (o, body) in BUILTIN.items():
ctl = mi[o:o + 0x880]
if hashlib.sha256(ctl).hexdigest()[:16] != key: sys.exit(f'【红】main @{o:#x} 控制段哈希与内嵌内核键 {key} 不符')
with tempfile.TemporaryDirectory() as t:
src = os.path.join(t, 'k.comp'); open(src, 'w').write(BUILTIN_GLSL.replace('BODY', body))
r = subprocess.run([glslc, '--target-env=vulkan1.1', '-O', src, '-o', os.path.join(t, 'k.spv')], capture_output=True, text=True)
if r.returncode: sys.exit('【红】内嵌内核编译失败:' + r.stderr)
spv = open(os.path.join(t, 'k.spv'), 'rb').read()
refl = {'key': key, 'stage': 'cs', 'c1': '', 'local': [32, 1, 1], 'inputs': [], 'caps': [1], 'frag_out_map': 0,
'bindings': [{'binding': 0, 'vk_type': 6, 'kind': 'cbuf', 'reg': 0},
{'binding': 1, 'vk_type': 7, 'kind': 'sbuf', 'reg': 0, 'rw': False},
{'binding': 2, 'vk_type': 7, 'kind': 'sbuf', 'reg': 1, 'rw': True}]}
res.append((key, ctl, refl, spv))
return res
def main():
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_vk_', dir=os.environ.get('WORK'))
packs, jobs, c1s, ctls = {}, {}, {}, {}
pack_only = os.environ.get('PACK_ONLY') == '1'
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(HERE, '../../verify')); import nsoimg
packs['main'] = nsoimg.load(MAIN)
rec = main_rec(packs['main'], k)
else:
if name not in packs: packs[name] = records(open(os.path.join(dm_dir, name), 'rb').read())
rec = packs[name][k]
ci = rec.find(bytes.fromhex('34127698'))
if hashlib.sha256(rec[ci:ci + 0x880]).hexdigest()[:16] != key: sys.exit(f'【红】{name}#{k} 控制段哈希与键 {key} 不符')
ctls[key] = rec[ci:ci + 0x880]
if not pack_only: jobs[key], c1s[key] = job_for(key, name, rec, w)
if 'main' not in packs and os.environ.get('GLSLC'):
sys.path.insert(0, os.path.join(HERE, '../../verify')); import nsoimg
packs['main'] = nsoimg.load(MAIN)
if pack_only:
shutil.rmtree(w, ignore_errors=True)
st = {r['key']: r['st'] for r in json.load(open(os.path.join(out, '_vk_build.json')))}
ents = [(k, ctls[k], json.load(open(os.path.join(out, k + '.vk.json'))), open(os.path.join(out, k + '.spv'), 'rb').read())
for k in keys if st.get(k) == 'ok']
emit_runtime(ents + builtin_entries(packs.get('main', b''))); return
chunks = [c for c in (keys[i::NJ] for i in range(NJ)) if c]
def xl(ch):
jp = os.path.join(w, f'job_{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, chunks))
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 xerr: return key, 'xlate: ' + xerr[key], None
st, refl = finish(key, w, jobs[key], c1s[key], *loc[key])
return key, st, refl
with cf.ThreadPoolExecutor(NJ) as ex: res = list(ex.map(fin, keys))
shutil.rmtree(w, ignore_errors=True)
st = collections.Counter(r[1].split(':')[0] for r in res)
print(f'着色器 {len(res)}:' + ','.join(f'{k} {v}' for k, v in st.most_common()))
for e, n in collections.Counter(r[1] for r in res if r[1] != 'ok').most_common(12): print(f' {n:5d} {e}')
ok = [r[2] for r in res if r[2]]
for e, n in collections.Counter(u for x in ok for u in x.get('unresolved', [])).most_common(8): print(f' 未解绑定 {n:5d} {e}')
for e, n in collections.Counter(c for x in ok for c in x['caps']).most_common(): print(f' cap {e}: {n}')
for e, n in collections.Counter(c for x in ok for c in x['exts']).most_common(): print(f' ext {e}: {n}')
dr = collections.Counter()
for x in ok:
for bank, d in x['drv_reads'].items():
dr[f'c{bank} dyn'] += d['dynamic']
for o in d['offsets']: dr[f'c{bank}+{o:#x}'] += 1
print('驱动段读取(前 20):', ', '.join(f'{k}×{v}' for k, v in dr.most_common(20)))
json.dump([{'key': r[0], 'st': r[1]} for r in res], open(os.path.join(out, '_vk_build.json'), 'w'), ensure_ascii=False)
emit_runtime([(r[0], ctls[r[0]], r[2], open(os.path.join(out, r[0] + '.spv'), 'rb').read()) for r in res if r[1] == 'ok']
+ builtin_entries(packs.get('main', b'')))
if __name__ == '__main__': main()
+5 -1
View File
@@ -93,6 +93,10 @@ static class SwshXlate
false /* 不做 Y 取反 | no Y flip */, true /* 原点左上 | origin upper-left */, false);
}
public bool QueryHostSupportsTextureShadowLod() => true;
// 作业 sb_align:宿主存储缓冲偏移对齐(Adreno 64)。大于 NVN 的 16 时,着色器按 base & -sb_align 求偏移,宿主下对齐绑定、不再拷贝
// Job sb_align: host storage buffer offset alignment (Adreno 64). Above NVN's 16, shaders take offsets from base & -sb_align, so the host binds aligned down without copying
public int QueryHostStorageBufferOffsetAlignment() => _job["sb_align"] is JsonNode n ? (int)n : 16;
public bool QueryHasUnalignedStorageBuffer() => QueryHostStorageBufferOffsetAlignment() > 16;
// 作业 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;
@@ -126,7 +130,7 @@ static class SwshXlate
{
["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,
["sb_align"] = acc.QueryHostStorageBufferOffsetAlignment(), ["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 });